Caused by: java.lang.IllegalStateException: GoogleApiClient is not connected yet

后端 未结 5 656
暖寄归人
暖寄归人 2021-01-18 02:13

I am getting this error message when trying to implement logout for Google Sign-In for Android:

Caused by: java.lang.IllegalStateException: GoogleApiClient i         


        
相关标签:
5条回答
  • 2021-01-18 02:50

    To make a button Sign Out in another Activity, for example: the login is in the Activity A and the sign out is in the activity B, then you can use this for the second activity.

    First create the OnStart method:

     @Override
    protected void onStart() {
        GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
                .requestEmail()
                .build();
        mGoogleApiClient = new GoogleApiClient.Builder(this)
                .addApi(Auth.GOOGLE_SIGN_IN_API, gso)
                .build();
        mGoogleApiClient.connect();
        super.onStart();
    }
    

    After in your button collocate this:

    Auth.GoogleSignInApi.signOut(mGoogleApiClient).setResultCallback(
        new ResultCallback<Status>() {
            @Override
            public void onResult(Status status) {
                // ...
                Toast.makeText(getApplicationContext(),"Logged Out",Toast.LENGTH_SHORT).show();
                Intent i=new Intent(getApplicationContext(),MainActivity.class);
                startActivity(i);
            }
        });
    
    0 讨论(0)
  • 2021-01-18 02:57

    you can check whether is connected or not.

     if (mGoogleApiClient.isConnected()) {
    
              //your code
      }
    
    0 讨论(0)
  • 2021-01-18 03:00

    I know its quite old post and already answered.

    However, the actual cause of the error is not object creation at single or multiple places but "enableAutoManage" invocation at the time of Building Client object.

    The API doc here suggests that it would automatically do the life cycle management by calling methods on onStart & onStop methods of the activity.

    Therefore, if you want to use the same object across different activities then you should avoid calling "enableAutoManage" and invoke apiObject.connect(preferably in onStart of activity) and apiObject.disconnect() (preferably in onStop of activity).

    This worked for me, therefore sharing.

    0 讨论(0)
  • 2021-01-18 03:01

    Remove this:

    .enableAutoManage(this /* FragmentActivity */, this /* OnConnectionFailedListener */)

    0 讨论(0)
  • 2021-01-18 03:06

    You should ditch the threading and just create a second GoogleApiClient. According to this post (https://stackoverflow.com/a/25190497/608347) the client isn't a heavy object so might as well avoid the confusing design and make things simple. Even if you dont go down this path you should strip out that #setClient and #getClient code and see if you get the same error when disconnecting from a single activity

    0 讨论(0)
提交回复
热议问题