1.準(zhǔn)備工作
首先得在谷歌開(kāi)發(fā)控制臺(tái)https://console.developers.google.com 創(chuàng)建自己的項(xiàng)目乐严,并配好相關(guān)的信息,如圖
2.在你的project的gradle注入谷歌服務(wù)的依賴 classpath 'com.google.gms:google-services:3.0.0'
然后在你的app的gradle中加入compile 'com.google.android.gms:play-services-auth:9.6.1'依賴掉缺, 并在最底部引入apply plugin: 'com.google.gms.google-services'
記得在app目錄下的加入google-services.json文件
好了卜录,配置基本完成,接下來(lái)就是在你的登陸頁(yè)面擼登陸的代碼了
1.初始化Google 可以參考谷歌官方api https://developers.google.com/+/mobile/android/getting-started
/**
* Google登錄初始化
*/
public void initGooglePlus() {
GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestId()
.requestProfile()
.requestEmail()
.build();
mGoogleApiClient = new GoogleApiClient.Builder(this)
.enableAutoManage(this, this)
.addApi(Auth.GOOGLE_SIGN_IN_API, gso)
.build();
}
點(diǎn)擊登陸按鈕
/**
* 登陸
*/
public void googleSignIn() {
Intent intent = Auth.GoogleSignInApi.getSignInIntent(mGoogleApiClient);
startActivityForResult(intent, G_SIGN_IN);
}
回調(diào)
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == G_SIGN_IN) {
GoogleSignInResult result = Auth.GoogleSignInApi.getSignInResultFromIntent(data);
handleSignInResult(result);
}
}
獲取回調(diào)返回的用戶相關(guān)信息
/**
* Google plus 登陸回調(diào)
*/
private void handleSignInResult(GoogleSignInResult result) {
showLog("handleSignInResult----" + result.isSuccess());
if (result.isSuccess()) {
GoogleSignInAccount account = result.getSignInAccount();
showLog("id--------" + account.getId() + "----name----" + account.getDisplayName() + "---photo--" + account.getPhotoUrl());
}
}
好了眶明,簡(jiǎn)單的完成google登陸了艰毒,不過(guò)還有退出等邏輯,這里就不寫(xiě)了