要实现Android Studio中的谷歌登录弹出功能,你可以按照以下步骤操作:
implementation 'com.google.android.gms:play-services-auth:19.2.0'
import com.google.android.gms.auth.api.signin.GoogleSignIn;
import com.google.android.gms.auth.api.signin.GoogleSignInOptions;
import com.google.android.gms.auth.api.signin.GoogleSignInClient;
import com.google.android.gms.common.SignInButton;
public class MainActivity extends AppCompatActivity {
private GoogleSignInClient mGoogleSignInClient;
private int RC_SIGN_IN = 1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// 配置Google登录选项
GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestEmail()
.build();
// 构建GoogleSignInClient对象
mGoogleSignInClient = GoogleSignIn.getClient(this, gso);
// 设置Google登录按钮样式
SignInButton signInButton = findViewById(R.id.google_login_button);
signInButton.setSize(SignInButton.SIZE_STANDARD);
// 设置Google登录按钮点击事件
signInButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// 启动Google登录流程
Intent signInIntent = mGoogleSignInClient.getSignInIntent();
startActivityForResult(signInIntent, RC_SIGN_IN);
}
});
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// 处理Google登录结果
if (requestCode == RC_SIGN_IN) {
Task task = GoogleSignIn.getSignedInAccountFromIntent(data);
try {
// 成功登录,获取Google登录用户信息
GoogleSignInAccount account = task.getResult(ApiException.class);
String displayName = account.getDisplayName();
String email = account.getEmail();
// TODO: 在此处处理登录成功后的逻辑
} catch (ApiException e) {
// Google登录失败
Log.w(TAG, "Google sign in failed", e);
}
}
}
}
这样,当用户点击“Google Login”按钮时,将会弹出谷歌登录界面。用户成功登录后,你可以在onActivityResult()
方法中处理登录成功后的逻辑。