Error in Fragment: “Already managing a GoogleApiClient with id 0”

后端 未结 10 1943
独厮守ぢ
独厮守ぢ 2020-12-13 08:16

Everything works right the first time, if you launch a second time you see this error:

FATAL EXCEPTION: main
Process         


        
10条回答
  •  南方客
    南方客 (楼主)
    2020-12-13 08:41

    The checked answer will not work if you use Login fragment in an Activity multiple times, because adding the fragment sequentially in a short time will lead the same crash. Android sometimes mixes lifecycle of Fragments added in an Activity.

    So I advice you to do mGoogleApiClient staff in a separate abstract Activity, and make all activities adding Login fragment extend this Activity.

    I have managed to get rid of this crash by creating this abstract Activity below, just copy paste it to your project:

    abstract class LoginableActivity : BaseActivity() {
    
        lateinit var googleApiClient: GoogleApiClient
    
        override fun onCreate(savedInstanceState: Bundle?) {
            super.onCreate(savedInstanceState)
    
            val gso = GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
                .requestIdToken(getString(R.string.fcm))
                .requestEmail()
                .build()
    
            googleApiClient = GoogleApiClient.Builder(this)
                .enableAutoManage(this, 1, null)
                .addApi(Auth.GOOGLE_SIGN_IN_API, gso)
                .build()
        }
    
        override fun onStart() {
            super.onStart()
            if (!googleApiClient.isConnected && !googleApiClient.isConnecting) {
                googleApiClient.connect()
            }
        }
    
        override fun onStop() {
            super.onStop()
            if (googleApiClient.isConnected) {
                googleApiClient.stopAutoManage(this)
                googleApiClient.disconnect()
            }
        }
    }
    

    After you moved googleApiClient to LoginableActivity you can access googleApiClient from Login fragment like this (let's do it with Java):

    final Activity = getActivity();
    if (activity instanceof LoginableActivity) {
        final GoogleApiClient googleApiClient = ((LoginableActivity) activity).googleApiClient;
    }
    

提交回复
热议问题