Google Api Client already managing with id 0

放肆的年华 提交于 2019-12-20 04:52:55

问题


I want to connect GoogleApiClient in activity. It works fine when user click button first time and this dialog appears but when user press back button and reclick the button that responsable for initializing GoogleApiClient, I get this error

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

Here is my GoogleApiClient implementation

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

Call initGoogleApiClient method when user press button

btnApiClient.setOnClickListener {
        initGoogleApiClient()
}

I checked this answer and add stopAutoManage method but still get same error. Also checked documentation and it says

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.

So I change my initGoogleApiClient method and add stopAutoManage method before init but this time nothing happens after first click

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

}

Also I have only got this two dependencies

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

Any help will be appriciated

来源:https://stackoverflow.com/questions/56037170/google-api-client-already-managing-with-id-0

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!