程式碼實現 Google SignIn

  • 在登入活動的 onCreate 方法中,配置 Google 登入以請求你的應用所需的使用者資料。
 GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
        .requestEmail()
        .build();
  • 建立一個 GoogleApiClient 物件,可以訪問 Google 登入 API 和你指定的選項。
 mGoogleApiClient = new GoogleApiClient.Builder(this)
        .enableAutoManage(this /* FragmentActivity */, this /* OnConnectionFailedListener */)
        .addApi(Auth.GOOGLE_SIGN_IN_API, gso)
        .build();
  • 現在,當使用者點選 Google 登入按鈕時,請呼叫此功能。

     private void signIn() {
     Intent signInIntent = Auth.GoogleSignInApi.getSignInIntent(mGoogleApiClient);
     startActivityForResult(signInIntent, RC_SIGN_IN);
    }
    
  • 實現 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 == RC_SIGN_IN) {
        GoogleSignInResult result = Auth.GoogleSignInApi.getSignInResultFromIntent(data);
        handleSignInResult(result);
    }
}
  • 最後一步處理結果並獲取使用者資料

     private void handleSignInResult(GoogleSignInResult result) {
     Log.d(TAG, "handleSignInResult:" + result.isSuccess());
     if (result.isSuccess()) {
         // Signed in successfully, show authenticated UI.
         GoogleSignInAccount acct = result.getSignInAccount();
         mStatusTextView.setText(getString(R.string.signed_in_fmt, acct.getDisplayName()));
         updateUI(true);
     } else {
         // Signed out, show unauthenticated UI.
         updateUI(false);
     }
    }