一、注册应用
SHA-1 必须添加
二、下载配置文件
三、添加SDK
1. 项目级 build.gradle
buildscript {
dependencies {
// Add this line
classpath 'com.google.gms:google-services:4.2.0'
}
}
2. 应用级 build.gradle
dependencies {
// Add this line
implementation 'com.google.firebase:firebase-core:16.0.9'
implementation 'com.google.firebase:firebase-auth:16.1.0'
implementation 'com.google.android.gms:play-services-auth:16.0.1'
}
...
// Add to the bottom of the file
apply plugin: 'com.google.gms.google-services'
四、启用Google登录功能
五、使用 Firebase 进行Google身份验证
private static final String TAG = "MainActivity";
private int RC_SIGN_IN = 1;
private GoogleSignInClient mGoogleSignInClient;
private FirebaseAuth mAuth;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
// 服务器的客户端 ID
.requestIdToken(getString(R.string.default_web_client_id))
.requestEmail()
.build();
mGoogleSignInClient = GoogleSignIn.getClient(this, gso);
mAuth = FirebaseAuth.getInstance();
// 谷歌登录按钮
findViewById(R.id.btn_login).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
signIn();
}
});
}
/**
* 调用谷歌登陆
*/
private void signIn() {
Intent signInIntent = mGoogleSignInClient.getSignInIntent();
startActivityForResult(signInIntent, RC_SIGN_IN);
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
//
if (requestCode == RC_SIGN_IN) {
Task<GoogleSignInAccount> task = GoogleSignIn.getSignedInAccountFromIntent(data);
try {
// 谷歌登陆成功,获取谷歌账号信息
GoogleSignInAccount account = task.getResult(ApiException.class);
firebaseAuthWithGoogle(account);
} catch (ApiException e) {
// 谷歌登录失败
Log.e(TAG, "Google sign in failed", e);
}
}
}
private void firebaseAuthWithGoogle(GoogleSignInAccount acct) {
Log.d(TAG, "firebaseAuthWithGoogle:" + acct.getId());
// showProgressDialog();
// 异步任务
AuthCredential credential = GoogleAuthProvider.getCredential(acct.getIdToken(), null);
mAuth.signInWithCredential(credential)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
@Override
public void onComplete(@NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
// 登录成功
Log.d(TAG, "signInWithCredential:success");
final FirebaseUser user = mAuth.getCurrentUser();
Log.d(TAG, "uid:" + user.getUid());
Log.d(TAG, "email:" + user.getEmail());
Log.d(TAG, "name:" + user.getDisplayName());
Log.d(TAG, "phone:" + user.getPhoneNumber());
Log.d(TAG, "providerid:" + user.getProviderId());
Toast.makeText(MainActivity.this, user.getUid(), Toast.LENGTH_SHORT).show();
} else {
// 登录失败
Log.e(TAG, "signInWithCredential:failure", task.getException());
Toast.makeText(MainActivity.this, "Authentication Failed.", Toast.LENGTH_SHORT).show();
}
// hideProgressDialog();
}
});
}
六、常见问题
1. 12500异常
添加支持电子邮件地址地址