Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check whether the user is already logged in using Auth.GoogleSignInApi?

I fount that in order to sign in the user I have to use this code:

Intent signInIntent = Auth.GoogleSignInApi.getSignInIntent(mGoogleApiClient);
startActivityForResult(signInIntent, RC_SIGN_IN);

to signout

new ResultCallback<Status>() {
                @Override
                public void onResult(Status status) {
                    disconnect();
                }
            });

But when the user relaunch the app and he is already logged in (and no sign out before) is it possible to detect this 'currently logged in' state?

Obviously, it is possible to save 'logged in' in the settings (shared preferences) of the app but is where any way to detect using google api?

like image 953
Vyacheslav Avatar asked Feb 04 '16 08:02

Vyacheslav


2 Answers

Here I found the solution:

  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);
                }
            });
        }
like image 147
Vyacheslav Avatar answered Sep 30 '22 12:09

Vyacheslav


Here I found the simple solutions for this

GoogleSignInAccount lastSignedInAccount= GoogleSignIn.getLastSignedInAccount(context);
if(lastSignedInAccount==null){
// user has already logged in, you can check user's email, name etc from lastSignedInAccount
String email = lastSignedInAccount.getEmail();
}else{
// user is not logged in with any account
}
like image 26
Kimmi Dhingra Avatar answered Sep 30 '22 14:09

Kimmi Dhingra