It might be a little bit complicated, but Google already huge provided Docs about this usage.
To request stored credentials, you must create an instance of GoogleApiClient
configured to access the Credentials API.
mCredentialsApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.enableAutoManage(this, this)
.addApi(Auth.CREDENTIALS_API)
.build();
A CredentialRequest object specifies the sign-in systems from which you want to request credentials. Build a CredentialRequest
using the setPasswordLoginSupported
method for password-based sign-in, and the setAccountTypes()
method for federated sign-in services such as Google Sign-In.
mCredentialRequest = new CredentialRequest.Builder()
.setPasswordLoginSupported(true)
.setAccountTypes(IdentityProviders.GOOGLE, IdentityProviders.TWITTER)
.build();
After you have created GoogleApiClient
and CredentialRequest
objects, pass them to the CredentialsApi.request()
method to request credentials stored for your app.
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());
}
}
});
On a successful credential request, use the resulting Credential object to complete the user's sign-in to your app. Use the getAccountType()
method to determine the type of retrieved credentials, then complete the appropriate sign-in process.
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);
// ...
}
}