Search code examples
androidandroid-lifecycleandroid-architecture-lifecycle

When does a LifecycleRegistry instance start listening to LifecycleOwner's lifecycle changes?


I've started learning architecture components, but can't find one thing.

LifecycleFragment just creates a new LifecycleRegistry object, which does not start observing the fragment's lifecycle.

I guess the LifecycleRegistry object starts listening to the fragment's lifecycle when we, for example, put it into LiveData.observe() as first param, but I haven't found any proof of this in source code.

Question: When and how does a LifecycleRegistry object start to observe a fragment's lifecycle and refresh LifecycleRegistry.mState?


Solution

  • There is a ContentProvider called LifecycleRuntimeTrojanProvider that is merged into the app's AndroidManifest.xml. In its onCreate method it initializes a singleton called LifecycleDispatcher, which is responsible for updating all LifecycleRegistry instances.

    LifecycleDispatcher uses the Application.registerActivityLifecycleCallbacks method that has been around since API 14 to get notified when a new activity is created. At this point it injects an instance of ReportFragment into the activity. The ReportFragment uses the Fragment lifecycle callbacks to update the activity's LifecycleRegistry if necessary, like this:

    @Override
    public void onStop() { // Showing onStop as example
        super.onStop();
        dispatch(Lifecycle.Event.ON_STOP);
    }
    
    private void dispatch(Lifecycle.Event event) {
        if (getActivity() instanceof LifecycleRegistryOwner) {
            ((LifecycleRegistryOwner) getActivity()).getLifecycle().handleLifecycleEvent(event);
        }
    }
    

    If the new activity is a FragmentActivity, the LifecycleDispatcher calls FragmentManager.registerFragmentLifecycleCallbacks to get notified of the activity's fragments lifecycle events. It relays the onFragmentCreated, onFragmentStarted and onFragmentResumed callbacks to the LifecycleRegistry in case the fragment is a LifecycleRegistryOwner, in the same way as before.

    The onFragmentPaused, onFragmentStopped, and onFragmentDestroyed callbacks are called after the corresponding callbacks are called on the fragment, but the LifecycleObserver callbacks must be called before. So whenever a fragment is created, the LifecycleDispatcher injects an instance of LifecycleDispatcher.DestructionReportFragment into it. The DestructionReportFragment's lifecycle callbacks are used to update the registry for the pause, stop and destroy events.

    I can't link to the code because it hasn't been released yet, but you can browse it in Android Studio after you add the library to your project.