wverdese
wverdese

Reputation: 159

GoogleApiClient: Can't manually connect and perform signOut afterwards

I want to manually handle the connect() and disconnect() operation on the GoogleApiClient. I'm trying to:

Here's an example:

fun signOut(googleApiClient: GoogleApiClient, resultCallback: (Status) -> Unit) {
    Auth.GoogleSignInApi.signOut(googleApiClient).setResultCallback(resultCallback)
}

fun test() {
    val googleApiClient = GoogleApiClient.Builder(activity)
        .addApi(Auth.GOOGLE_SIGN_IN_API, buildGoogleSignInOptions(googleAuthId))
        .build()
    googleApiClient.registerConnectionCallbacks(object : ConnectionCallbacks {
        override fun onConnected(connectionHint: Bundle?) {
            signOut { status ->
                //TODO something with status
                googleApiClient.disconnect()
            }
        }

        override fun onConnectionSuspended(cause: Int) {
            //nop
        }
    })
    googleApiClient.registerConnectionFailedListener {
        //TODO handle failure
    }
    googleApiClient.connect()
}

However when onConnected() is called the signOut call fails with

IllegalStateException: GoogleApiClient is not connected yet 

Am I doing something wrong or is it a bug from the library?

Upvotes: 1

Views: 354

Answers (1)

Chicken Pro
Chicken Pro

Reputation: 86

We need create googleAPIClient in onCreate() and sign out it in same activity.

Ex: In onCreate()

    GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
            .requestIdToken(this.getString(R.string.default_web_client_id))
            .requestEmail()
            .requestProfile()
            .build();


    mGoogleApiClient = new GoogleApiClient.Builder(activity)
            .enableAutoManage(activity, new GoogleApiClient.OnConnectionFailedListener() {
                @Override
                public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
                }
            })
            .addConnectionCallbacks(new GoogleApiClient.ConnectionCallbacks() {
                @Override
                public void onConnected(@Nullable Bundle bundle) {
                }

                @Override
                public void onConnectionSuspended(int i) {

                }
            })
            .addApi(Auth.GOOGLE_SIGN_IN_API, gso)
            .build();

And Sign out it :

    Auth.GoogleSignInApi.signOut(mGoogleApiClient).setResultCallback(
            new ResultCallback<Status>() {
                @Override
                public void onResult(@NonNull Status status) {

                    if (mListener != null) {
                        mListener.onSigout("");
                    }
                }
            });

If we create mGoogleAPIClient with ApplicationContext, we can't sign out Google Account properly.

Upvotes: 1

Related Questions