Silent sign in to retrieve token with GoogleApiClient Silent sign in to retrieve token with GoogleApiClient android android

Silent sign in to retrieve token with GoogleApiClient


Yes, answer above is correct. In general, any GoogleApiClient needs to be connected before it can return you any data. enableAutoManage helps you to call connect() / disconnect() automatically during onStart() / onStop(). If you don't use autoManage, you will need to connect() manually.

And even better, you should disconnect in a finally block.

Assuming you are not on the UI thread.

try {    ConnectionResult result = mGoogleApiClient.blockingConnect();    if (result.isSuccess()) {        GoogleSignInResult googleSignInResult =            Auth.GoogleSignInApi.silentSignIn(googleApiClient).await();    ...    }} finally {    mGoogleApiClient.disconnect();}

And also, to clean up your code a little bit:1. gso built from below configuration is identical to your pasted code above:

GoogleSignInOptions gso =   new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)        .requestIdToken(SERVER_CLIENT_ID)        .requestEmail()        .build();
  1. Based on your current logic, addOnConnectionFailedListener / addConnectionCallbacks doesn't help other than adb log. Maybe just remove them completely?


I found the problem. I was under the impression that the function

OptionalPendingResult<GoogleSignInResult> pendingResult = Auth.GoogleSignInApi.silentSignIn(googleApiClient);

was going to connect the mGoogleApiClient for me (since it returns a pending result). However, that was not the case and in order to solve the above I just needed to add the call

ConnectionResult result = mGoogleApiClient.blockingConnect();

in the beginning of the silentLogin method. (and then of course disconnect later on, and also make sure the call is made in a thread different from main thread)

tada'


To add to the two answers above by Isabella and Ola, if you're using the new sign in lib with Firebase:

FirebaseAuth.getInstance().currentUser?.let{     //create sign-in options the usual way    val googleSignInClient = GoogleSignIn.getClient(context, gso)    googleSignInClient.silentSignIn().addOnCompleteListener {        val account: GoogleSignInAccount? = it.result        //get user info from account object    }}

Also, this can be called from the UI thread. FirebaseAuth.getInstance().currentUser will always return the user object if you have signed in once before.