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

后端 未结 10 1941
独厮守ぢ
独厮守ぢ 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:48

    The official doc for enableAutoManage says this:

    At any given time, only one auto-managed client is allowed per id. To reuse an id you must first call stopAutoManage(FragmentActivity) on the previous client.

    Your code is using the version of enableAutoManage without a clientId parameter, so it's defaulting to 0. Below I explain why you will have multiple auto-managed clients for clientId 0, which is what the above documentation is warning against.

    After your Login Fragment is attached to a FragmentActivity, it tells that activity to start managing a new instance of GoogleApiClient. But what if the FragmentActivity is already managing another instance of GoogleApiClient? That's when you get the error.

    There are a few possible scenarios that can lead up to this multiple-GoogleApiClients-per-FragmentActivity situation.

    • The FragmentActivity has another Fragment in addition to Login that creates a GoogleApiClient and also asks the FragmentActivity to manage it.
    • The FragmentActivity itself creates a GoogleApiClient and starts managing it before Login Fragment is attached to the FragmentActivity.
    • Maybe you add Login Fragment in a FragmentTransaction and you call addToBackStack. Then the user taps back, then later somehow the Login Fragment is re-attached. In this case, the important Login Activity method calls are onCreateView -> onDestroyView -> onCreateView as shown here:

    This is problematic because the second call to Login.onCreateView tries to have FragmentActivity manage a second GoogleApiClient.

    If I were you, I'd seriously consider creating the GoogleApiClient in the activity instead of in any fragments. Then you could either do the work that requires GoogleApiClient in the Activity, or continue to do it in Login Fragment after getting the GoogleApiClient from the Activity like so:

    private GoogleApiClient googleApiClient;
    
    @Override
    void onAttach(Activity activity) {
        super.onAttach(activity);
        googleApiClient = activity.getGoogleApiClient();
    }
    
    @Override
    void onDetach() {
        super.onDetach();
        googleApiClient = null;
    }
    

提交回复
热议问题