Firebase Auth - Google login
使用Firebase來做Google Login,
- 1.在dependencies加入
dependencies {
compile 'com.google.firebase:firebase-auth:9.6.1'
compile compile 'com.google.android.gms:play-services-auth:9.6.1'
}
- 2.再來就是要處理Google Auth Login流程
//建立請求項目
GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestIdToken(getString(R.string.default_web_client_id))
.requestEmail()
.requestProfile()
.build();
//建立GoogleApiClient物件 GoogleApiClient mGoogleApiClient = new GoogleApiClient.Builder(this)
.enableAutoManage(this , this )
.addApi(Auth.GOOGLE_SIGN_IN_API, gso)
.build();
//發出Auth login ,會跑出google帳號選單
Intent signInIntent = Auth.GoogleSignInApi.getSignInIntent(mGoogleApiClient);
startActivityForResult(signInIntent, GOOGLE_AUTH_REQUEST_CODE);
- 3.最後在onActivityResult取得結果
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// Result returned from launching the Intent from GoogleSignInApi.getSignInIntent(...);
if (requestCode == GOOGLE_AUTH_REQUEST_CODE) {
GoogleSignInResult result = Auth.GoogleSignInApi.getSignInResultFromIntent(data);
if (result.isSuccess()) {
// Google Sign In was successful, authenticate with Firebase
GoogleSignInAccount account = result.getSignInAccount();
firebaseAuthWithGoogle(account);
}
}
}
- 4. 最後取得GoogleSignInAccount物件丟給FireBase處理,就完成登入
private void firebaseAuthWithGoogle(GoogleSignInAccount acct) {
Log.d(TAG, "firebaseAuthWithGoogle:" + acct.getId());
AuthCredential credential = GoogleAuthProvider.getCredential(acct.getIdToken(), null);
mAuth.signInWithCredential(credential)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
@Override
public void onComplete(@NonNull Task<AuthResult> task) {
Log.d(TAG, "signInWithCredential:onComplete:" + task.isSuccessful());
// If sign in fails, display a message to the user. If sign in succeeds
// the auth state listener will be notified and logic to handle the
// signed in user can be handled in the listener.
if (!task.isSuccessful()) {
Log.w(TAG, "signInWithCredential", task.getException());
Toast.makeText(LoginActivity.this, "Authentication failed.",
Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(LoginActivity.this, "login success",
Toast.LENGTH_SHORT).show();
finish();
}
// ...
}
});
}