谷歌账户登录开发示例(集成)
最近项目上业务需要,查的资料说的比较乱(主要是集成那块)
1,修改app的build.gradle,增加
implementation'com.google.android.gms:play-services-auth:18.0.0'
2,布局文件中登录按钮
<com.google.android.gms.common.SignInButton
android:id="@+id/sign_in_button"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
3,登录相关代码
SignInButton signInButton = findViewById(R.id.sign_in_button);
signInButton.setSize(SignInButton.SIZE_WIDE);
GoogleSignInOptions gso =new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestEmail()
.requestId()
.build();
mGoogleSignInClient = GoogleSignIn.getClient(this, gso);
signInButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent signInIntent =mGoogleSignInClient.getSignInIntent();
startActivityForResult(signInIntent, RC_SIGN_IN);
}
});
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// 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 task = GoogleSignIn.getSignedInAccountFromIntent(data);
handleSignInResult(task);
}
}
4,跳转处理
private GoogleSignInClientmGoogleSignInClient;
private int RC_SIGN_IN =10000;
private void handleSignInResult(Task completedTask) {
try {
GoogleSignInAccount account = completedTask.getResult(ApiException.class);
Log.w("Google email",account.getEmail());
Log.w("Google id",account.getId());
// Signed in successfully, show authenticated UI.
Intent intent =new Intent(LoginActivity.this,MainActivity.class);
startActivity(intent);
finish();
// updateUI(account);
}catch (ApiException e) {
// The ApiException status code indicates the detailed failure reason.
// Please refer to the GoogleSignInStatusCodes class reference for more information.
Log.w("Google login", "signInResult:failed code=" + e.getStatusCode());
// updateUI(null);
}
}