2017-02-01 54 views
1

我想手動處理GoogleApiClient上的connect()disconnect()操作。我想:GoogleApiClient:以後無法手動連接並執行signOut

  • 建新GoogleApiClient(不enableAutoManage
  • 呼叫connect()
  • onConnected()被稱爲執行呼叫disconnect()signOut
  • signOut超過

這裏的一個例子:

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() 
} 

然而,當onConnected()被稱爲signOut調用失敗

IllegalStateException: GoogleApiClient is not connected yet 

我是不是做錯了什麼或者是從庫中的錯誤?

+1

錯誤似乎與此[SO線程](http://stackoverflow.com/questions/29343922/googleapiclient-is-throwing-googleapiclient-is-not-connected-yet-after-onconne)相同,並且是解決。 – noogui

+0

@noogui謝謝!在'onCreate()'中移動客戶端創建聽起來比解決方案更具有解決方法,但我想我無能爲力了。正如它在這個線程中所說的那樣,沒有辦法向Google報告這個錯誤。 – wverdese

回答

1

我們需要在onCreate()中創建googleAPIClient並在同一活動中註銷它。

例: 在的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(); 

並註銷它:

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

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

如果我們的ApplicationContext創建mGoogleAPIClient,我們不能正確退出谷歌帳戶。

相關問題