我想手动处理connect()
上的disconnect()
和GoogleApiClient
操作。我想:
GoogleApiClient
(不含enableAutoManage
)connect()
onConnected()
时执行signOut
disconnect()
结束后致电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
我做错了什么或是库中的错误?
答案 0 :(得分: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,我们无法正确注销Google帐户。