Search code examples
androidgoogle-api-clientandroid-googleapiclientgoogle-signin

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?


Solution

  • 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);
                    }
                });
            }