Skip to content

Instantly share code, notes, and snippets.

@afiqiqmal
Created February 4, 2018 08:24
Show Gist options
  • Save afiqiqmal/2d54b43860b20585fde8079a0bb29d4f to your computer and use it in GitHub Desktop.
Save afiqiqmal/2d54b43860b20585fde8079a0bb29d4f to your computer and use it in GitHub Desktop.
Get Credential Email from android smartlock
public class LoginActivity extends BaseActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
...
...
CredentialsOptions options = new CredentialsOptions.Builder().forceEnableSaveDialog().build();
mCredentialsClient = Credentials.getClient(this, options);
requestCredentials();
}
private void requestCredentials() {
// Request all of the user's saved username/password credentials. We are not using
// setAccountTypes so we will not load any credentials from other Identity Providers.
CredentialRequest request = new CredentialRequest.Builder()
.setPasswordLoginSupported(true)
.setIdTokenRequested(true)
.build();
mCredentialsClient.request(request).addOnCompleteListener(
task -> {
if (task.isSuccessful()) {
// Successfully read the credential without any user interaction, this
// means there was only a single credential and the user has auto
// sign-in enabled.
processRetrievedCredential(task.getResult().getCredential());
return;
}
Exception e = task.getException();
if (e instanceof ResolvableApiException) {
// This is most likely the case where the user has multiple saved
// credentials and needs to pick one. This requires showing UI to
// resolve the read request.
ResolvableApiException rae = (ResolvableApiException) e;
try {
rae.startResolutionForResult(LoginActivity.this, Constant.SMARTLOCK_REQUEST);
} catch (IntentSender.SendIntentException e1) {
e1.printStackTrace();
}
return;
}
});
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case Constant.SMARTLOCK_REQUEST:
if (resultCode == RESULT_OK) {
Credential credential = data.getParcelableExtra(Credential.EXTRA_KEY);
processRetrievedCredential(credential);
}
break;
}
}
private void processRetrievedCredential(Credential credential) {
email.setText(credential.getId());
password.setText(credential.getPassword());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment