要在Android应用中实现谷歌登录,可以按照以下步骤进行操作:
implementation 'com.google.android.gms:play-services-auth:19.2.0'
private GoogleSignInClient mGoogleSignInClient;
private void createGoogleSignInClient() {
GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestEmail()
.build();
mGoogleSignInClient = GoogleSignIn.getClient(this, gso);
}
private static final int RC_SIGN_IN = 9001;
private void signIn() {
Intent signInIntent = mGoogleSignInClient.getSignInIntent();
startActivityForResult(signInIntent, RC_SIGN_IN);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == RC_SIGN_IN) {
Task task = GoogleSignIn.getSignedInAccountFromIntent(data);
handleSignInResult(task);
}
}
private void handleSignInResult(Task completedTask) {
try {
GoogleSignInAccount account = completedTask.getResult(ApiException.class);
// 登录成功,可以获取到用户的基本信息,例如账号、邮箱等
String email = account.getEmail();
String displayName = account.getDisplayName();
// 继续处理其他逻辑,例如跳转到主界面
} catch (ApiException e) {
// 登录失败,可以根据错误码进行处理
Log.e(TAG, "signInResult:failed code=" + e.getStatusCode());
}
}
通过以上步骤,你的应用就可以实现谷歌登录功能了。当用户点击登录按钮时,会跳转到谷歌登录页面,并且在登录成功后会返回用户的基本信息。你可以根据自己的需求进行进一步的处理。