使用新版 Firebase 后,他们改变了很多代码和操作方式。
现在,在设置 Firebase 项目时,他们提供了一个选项让你输入 AuthId,你可以下载 JSON 并将其粘贴到应用中。
在设置 ClientId 后,你可以添加以下代码来使 Google 登录恢复正常。
Button signInButton;
private static final int RC_SIGN_IN = 9001;
private GoogleApiClient mGoogleApiClient;
private FirebaseAuth mAuth;
private FirebaseAuth.AuthStateListener mAuthStateListener;
GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestIdToken(getString(R.string.default_web_client_id))
.requestEmail()
.build();
mGoogleApiClient = new GoogleApiClient.Builder(this)
.enableAutoManage(this , this )
.addApi(Auth.GOOGLE_SIGN_IN_API, gso)
.build();
mAuth = FirebaseAuth.getInstance();
mAuthStateListener = new FirebaseAuth.AuthStateListener() {
@Override
public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
FirebaseUser user = firebaseAuth.getCurrentUser();
updateUI(user);
}
};
@Override
protected void onStart() {
super.onStart();
mAuth.addAuthStateListener(mAuthStateListener);
mGoogleApiClient.connect();
}
@Override
protected void onStop() {
super.onStop();
if(mAuthStateListener != null) {
mAuth.removeAuthStateListener(mAuthStateListener);
}
mGoogleApiClient.disconnect();
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == RC_SIGN_IN) {
GoogleSignInResult result = Auth.GoogleSignInApi.getSignInResultFromIntent(data);
if (result.isSuccess()) {
GoogleSignInAccount account = result.getSignInAccount();
firebaseAuthWithGoogle(account);
} else {
updateUI(null);
}
}
}
private void firebaseAuthWithGoogle(GoogleSignInAccount acct) {
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()) {
Toast.makeText(LoginActivity.this, "Authentication failed.",
Toast.LENGTH_SHORT).show();
}
}
});
}
private void signIn() {
Intent signInIntent = Auth.GoogleSignInApi.getSignInIntent(mGoogleApiClient);
startActivityForResult(signInIntent, RC_SIGN_IN);
}
private void updateUI(FirebaseUser user) {
if (user != null) {
}
}
@Override
public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
Toast.makeText(this, "Google Play Services error.", Toast.LENGTH_SHORT).show();
}
public void GoogleSignIn(View v){
signIn();
}
@Override
protected void onRestart() {
super.onRestart();
mGoogleApiClient.connect();
}
这在我的应用程序中完全适用于使用Firebase进行Google身份验证。