Silent sign in to retrieve token with GoogleApiClient

浪子不回头ぞ 提交于 2019-11-27 21:16:42

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!