I am integrating Facebook and Google authentication in my android application.
While launching the application, I want to check if a user is logged on to the app with Facebook or Google authentication. I got success with Facebook using the below code:
if (Profile.getCurrentProfile() != null && AccessToken.getCurrentAccessToken() != null){
Intent i = new Intent(Splash.this, SecondActivity.class);
startActivity(i);
finish();
}
But having no success with Google. Also, I searched for many answers but most of them were using Firebase for Google authentication.
How would I achieve this using Google Authentication and not Firebase.
Help would be appreciated.
Thanks in advance!
We can use GoogleSignInApi.silentSignIn()
method to check if the login credential is valid or not.
It returns an OptionalPendingResult
object which is used to check whether the credential is valid or not. If the credential is valid OptionalPendingResult
's isDone()
method will return true.
The get method can then be used to obtain the result immediately (If it is available).
Android Documentation for OptionalPendingResult
:
https://developers.google.com/android/reference/com/google/android/gms/common/api/OptionalPendingResult
Android Documentation for GoogleSignInApi
:
https://developers.google.com/android/reference/com/google/android/gms/auth/api/signin/GoogleSignInApi
Here's the code for checking if the credentials are valid or not.
OptionalPendingResult<GoogleSignInResult> opr = Auth.GoogleSignInApi.silentSignIn(google_api_client);
if (opr.isDone()) {
// If the user's cached credentials are valid, the
// OptionalPendingResult will be "done" and the
// GoogleSignInResult will be available instantly.
Log.d("TAG", "Got cached sign-in");
GoogleSignInResult result = opr.get();
handleSignInResult(result);
}
@Override
public void onStart() {
super.onStart();
OptionalPendingResult<GoogleSignInResult> opr = Auth.GoogleSignInApi.silentSignIn(mGoogleApiClient);
if (opr.isDone()) {
// If the user's cached credentials are valid, the OptionalPendingResult will be "done"
// and the GoogleSignInResult will be available instantly.
Log.d(TAG, "Got cached sign-in");
GoogleSignInResult result = opr.get();
handleSignInResult(result);
} else {
// If the user has not previously signed in on this device or the sign-in has expired,
// this asynchronous branch will attempt to sign in the user silently. Cross-device
// single sign-on will occur in this branch.
showProgressDialog();
opr.setResultCallback(new ResultCallback<GoogleSignInResult>() {
@Override
public void onResult(GoogleSignInResult googleSignInResult) {
hideProgressDialog();
handleSignInResult(googleSignInResult);
}
});
}
}