这可能有点复杂,但 Google 已经大量提供了 Docs 关于这种用法的信息。
要请求存储的凭据,您必须创建一个配置为访问凭据 API 的 GoogleApiClient 实例。
mCredentialsApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.enableAutoManage(this, this)
.addApi(Auth.CREDENTIALS_API)
.build();
CredentialRequest 对象指定您要从中请求凭据的登录系统。使用setPasswordLoginSupported 方法构建CredentialRequest,用于基于密码的登录,setAccountTypes() 方法用于联合登录服务,例如 Google 登录。
mCredentialRequest = new CredentialRequest.Builder()
.setPasswordLoginSupported(true)
.setAccountTypes(IdentityProviders.GOOGLE, IdentityProviders.TWITTER)
.build();
创建GoogleApiClient 和CredentialRequest 对象后,将它们传递给CredentialsApi.request() 方法以请求为您的应用存储的凭据。
Auth.CredentialsApi.request(mCredentialsClient, mCredentialRequest).setResultCallback(
new ResultCallback<CredentialRequestResult>() {
@Override
public void onResult(CredentialRequestResult credentialRequestResult) {
if (credentialRequestResult.getStatus().isSuccess()) {
// See "Handle successful credential requests"
onCredentialRetrieved(credentialRequestResult.getCredential());
} else {
// See "Handle unsuccessful and incomplete credential requests"
resolveResult(credentialRequestResult.getStatus());
}
}
});
在凭据请求成功时,使用生成的凭据对象完成用户对您应用的登录。使用getAccountType() 方法确定检索到的凭据的类型,然后完成相应的登录过程。
private void onCredentialRetrieved(Credential credential) {
String accountType = credential.getAccountType();
if (accountType == null) {
// Sign the user in with information from the Credential.
signInWithPassword(credential.getId(), credential.getPassword());
} else if (accountType.equals(IdentityProviders.GOOGLE)) {
// The user has previously signed in with Google Sign-In. Silently
// sign in the user with the same ID.
// See https://developers.google.com/identity/sign-in/android/
GoogleSignInOptions gso =
new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestEmail()
.build();
mGoogleApiClient = new GoogleApiClient.Builder(this)
.enableAutoManage(this, this)
.addApi(Auth.GOOGLE_SIGN_IN_API, gso)
.setAccountName(credential.getId())
.build();
OptionalPendingResult<GoogleSignInResult> opr =
Auth.GoogleSignInApi.silentSignIn(mGoogleApiClient);
// ...
}
}