Android Studio Google account API安裝及使用

曾國維
6 min readJan 13, 2018

--

從這裡開始:https://developers.google.com/identity/sign-in/android/start-integrating

先到Google console建立專案:https://console.developers.google.com/?hl=zh-tw

到這裡註冊專案:https://developers.google.com/mobile/add?platform=android&cntapi=signin&cnturl=https:%2F%2Fdevelopers.google.com%2Fidentity%2Fsign-in%2Fandroid%2Fsign-in%3Fconfigured%3Dtrue&cntlbl=Continue%20Adding%20Sign-In

選擇連結的專案,android package name打上自com.(example).xxx.xxx,國家選台灣

接下來要產生SHA key,打開android studio 旁邊的gradle按下refresh(雙箭頭的)按下tasks->android->signingReport,打開右下角gradle console得到SHAkey複製並貼上,完成enable,按下載google-services.json,把這個檔案放到app/路徑下就算是完成了。

在build.gradle(Project level)把classpath 'com.google.gms:google-services:3.1.2'貼在dependencies裡面。

在build.gradle(Module:app)的dependencies(最後面)外層(最底行)貼上apply plugin: 'com.google.gms.google-services'。

在dependenciescompile 'com.google.android.gms:play-services-auth:11.8.0'

在layout裡面新增一個元件:com.google.android.gms.common.SignInButton來使用(比較有使用Google登入的感覺)

宣告GoogleSignInClient建置request,接下來Request之後收到activity result才可以get到user的資料

// Configure sign-in to request the user's ID, email address, and basic
// profile. ID and basic profile are included in DEFAULT_SIGN_IN.
GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN).requestEmail().build();
// Build a GoogleSignInClient with the options specified by gso.
mGoogleSignInClient = GoogleSignIn.getClient(this, gso);
private void sign_In(){//用一個登入按鈕來接,RC_SIGN_IN自己設
Intent signInIntent = mGoogleSignInClient.getSignInIntent();
startActivityForResult(signInIntent, RC_SIGN_IN);
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
System.out.println(requestCode);
// Result returned from launching the Intent from GoogleSignInClient.getSignInIntent(...);
if (requestCode == RC_SIGN_IN) {
// The Task returned from this call is always completed, no need to attach
// a listener.
Task<GoogleSignInAccount> task = GoogleSignIn.getSignedInAccountFromIntent(data);
handleSignInResult(task);
}
}
private void handleSignInResult(Task<GoogleSignInAccount> completedTask) {
try {//代表有成功
GoogleSignInAccount account = completedTask.getResult(ApiException.class);

// Signed in successfully, show authenticated UI.
//大概可以取的到這些
Log.d("TAG",
account.getDisplayName()+
account.getGivenName()+
account.getFamilyName()+
account.getEmail()+
account.getId()+
account.getPhotoUrl());
} catch (ApiException e) {//代表沒成功
// The ApiException status code indicates the detailed failure reason.
// Please refer to the GoogleSignInStatusCodes class reference for more information.
Log.w("TAG", "signInResult:failed code=" + e.getStatusCode());
updateUI(null);
}
}

最後是可以取得到的帳戶屬性:

https://developers.google.com/android/reference/com/google/android/gms/auth/api/signin/GoogleSignInAccount

--

--