已管理ID为0的Google Api客户端

时间:2019-05-08 09:06:29

标签: android kotlin google-api-client

我想在活动中连接GoogleApiClient。当用户第一次单击按钮并出现此对话框时,它运行良好,但是当用户按返回按钮并重新单击负责初始化GoogleApiClient的按钮时,出现此错误

java.lang.IllegalStateException: Already managing a GoogleApiClient with id 0

Google Api Client Dialog

这是我的GoogleApiClient实现

 private fun initGoogleApiClient() {
    mGoogleApiClient = GoogleApiClient.Builder(this)
        .addApi(Fitness.RECORDING_API)
        .addApi(Fitness.HISTORY_API)
        .addScope(Scope(Scopes.FITNESS_ACTIVITY_READ_WRITE))
        .addConnectionCallbacks(this)
        .enableAutoManage(this, 0, this)
        .build()
     }

override fun onResume() {
    super.onResume()
    mGoogleApiClient?.let {
        if (!it.isConnected) it.connect()
    }
}

override fun onPause() {
    super.onPause()
    mGoogleApiClient?.let {
        it.stopAutoManage(this)
        if (it.isConnected) it.disconnect()
    }
}

override fun onConnected(bundle: Bundle?) {
    Timber.d("onConnected")
}

override fun onConnectionSuspended(p0: Int) {
    Timber.d("onConnectionSuspended")
}

override fun onConnectionFailed(connectionResult: ConnectionResult) {
    Timber.d("onConnectionFailed")
}

用户按下按钮时调用initGoogleApiClient方法

btnApiClient.setOnClickListener {
        initGoogleApiClient()
}

我检查了this answer并添加了stopAutoManage方法,但仍然遇到相同的错误。还选中了documentation,它说

public abstract void stopAutoManage (FragmentActivity lifecycleActivity)
Disconnects the client and stops automatic lifecycle management. Use this before creating a new client (which might be necessary when switching accounts, changing the set of used APIs etc.).

This method must be called from the main thread.

因此,我更改了initGoogleApiClient方法,并在初始化之前添加了stopAutoManage方法,但这一次在第一次单击后没有任何反应

private fun initGoogleApiClient() {

mGoogleApiClient?.stopAutoManage(this)

mGoogleApiClient = GoogleApiClient.Builder(this)
    .addApi(Fitness.RECORDING_API)
    .addApi(Fitness.HISTORY_API)
    .addScope(Scope(Scopes.FITNESS_ACTIVITY_READ_WRITE))
    .addConnectionCallbacks(this)
    .enableAutoManage(this, 0, this)
    .build()

}

我也只有这两个依赖项

implementation 'com.google.android.gms:play-services-fitness:16.0.1'
implementation 'com.google.android.gms:play-services-auth:16.0.1'

任何帮助都将得到

0 个答案:

没有答案