Search code examples
androidonresumegoogle-signin

Android Google sign in api always call onResume()


Today, I am try implement Google Sign in API: https://developers.google.com/identity/sign-in/web/sign-in And implement interface GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener on MainActivity(AppCompatActivity). However, everything ok in the first time sign in. When I open the new Activity and back again, onConnected() always called. How to avoid onConnected() called when MainAcivity onResume ?


Solution

    1. After the first time you login OK -> google sign-in return token key for client which you can save to client (use SharedPreference).

    You can ref this code:

    YOu need edit your code to similar:

    GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
                    .requestEmail()
                    .requestIdToken("server_client_id") //to require server return Id token
                    .requestServerAuthCode("server_client_id") //to require server return authCode
                    .build();
    
    GoogleSignInResult result = Auth.GoogleSignInApi.getSignInResultFromIntent(data);
    GoogleSignInAccount acct = result.getSignInAccount();
    String personName = acct.getDisplayName();
    String personEmail = acct.getEmail();
    String personId = acct.getId();
    Uri personPhoto = acct.getPhotoUrl();
    String tokenKey = acct.getServerAuthCode(); //get authenticated code to save in client
    
    1. Open activity/app again -> before do sign-in again you have to check token key is exiting (stored or not) -> if is exiting then you do not sign-in again and of cource connected in listener not occour

    Cheer!