An implementation of Lifecycle that can handle multiple observers. It is used by Fragments and Support Library Activities. You can also directly use it if you have a custom LifecycleOwner.
protectedvoidonCreate(@Nullable Bundle savedInstanceState) { // Restore the Saved State first so that it is available to // OnContextAvailableListener instances mSavedStateRegistryController.performRestore(savedInstanceState); mContextAwareHelper.dispatchOnContextAvailable(this); super.onCreate(savedInstanceState); ReportFragment.injectIfNeededIn(this); if (BuildCompat.isAtLeastT()) { mOnBackPressedDispatcher.setOnBackInvokedDispatcher( Api33Impl.getOnBackInvokedDispatcher(this) ); } if (mContentLayoutId != 0) { setContentView(mContentLayoutId); } }
publicstaticvoidinjectIfNeededIn(Activity activity) { // sdk 29及其以上 if (Build.VERSION.SDK_INT >= 29) { // On API 29+, we can register for the correct Lifecycle callbacks directly LifecycleCallbacks.registerIn(activity); } // sdk 29以下 // Prior to API 29 and to maintain compatibility with older versions of // ProcessLifecycleOwner (which may not be updated when lifecycle-runtime is updated and // need to support activities that don't extend from FragmentActivity from support lib), // use a framework fragment to get the correct timing of Lifecycle events android.app.FragmentManagermanager= activity.getFragmentManager(); if (manager.findFragmentByTag(REPORT_FRAGMENT_TAG) == null) { manager.beginTransaction().add(newReportFragment(), REPORT_FRAGMENT_TAG).commit(); // Hopefully, we are the first to make a transaction. manager.executePendingTransactions(); } }
publicstaticvoidinjectIfNeededIn(Activity activity) { if (Build.VERSION.SDK_INT >= 29) { // On API 29+, we can register for the correct Lifecycle callbacks directly LifecycleCallbacks.registerIn(activity); } // Prior to API 29 and to maintain compatibility with older versions of // ProcessLifecycleOwner (which may not be updated when lifecycle-runtime is updated and // need to support activities that don't extend from FragmentActivity from support lib), // use a framework fragment to get the correct timing of Lifecycle events android.app.FragmentManagermanager= activity.getFragmentManager(); if (manager.findFragmentByTag(REPORT_FRAGMENT_TAG) == null) { manager.beginTransaction().add(newReportFragment(), REPORT_FRAGMENT_TAG).commit(); // Hopefully, we are the first to make a transaction. manager.executePendingTransactions(); } }
@Override publicvoidonDestroy() { super.onDestroy(); dispatch(Lifecycle.Event.ON_DESTROY); // just want to be sure that we won't leak reference to an activity mProcessListener = null; }
privatevoiddispatch(@NonNull Lifecycle.Event event) { if (Build.VERSION.SDK_INT < 29) { // Only dispatch events from ReportFragment on API levels prior // to API 29. On API 29+, this is handled by the ActivityLifecycleCallbacks // added in ReportFragment.injectIfNeededIn dispatch(getActivity(), event); } }
// this class isn't inlined only because we need to add a proguard rule for it (b/142778206) // In addition to that registerIn method allows to avoid class verification failure, // because registerActivityLifecycleCallbacks is available only since api 29. @RequiresApi(29) staticclassLifecycleCallbacksimplementsApplication.ActivityLifecycleCallbacks {
privatevoidmoveToState(State next) { if (mState == next) { return; } mState = next; if (mHandlingEvent || mAddingObserverCounter != 0) { mNewEventOccurred = true; // we will figure out what to do on upper level. return; } mHandlingEvent = true; sync(); mHandlingEvent = false; }
privatevoidinitViewTreeOwners() { // Set the view tree owners before setting the content view so that the inflation process // and attach listeners will see them already present ViewTreeLifecycleOwner.set(getWindow().getDecorView(), this); ViewTreeViewModelStoreOwner.set(getWindow().getDecorView(), this); ViewTreeSavedStateRegistryOwner.set(getWindow().getDecorView(), this); ViewTreeOnBackPressedDispatcherOwner.set(getWindow().getDecorView(), this); }
privatevoidinitViewTreeOwners() { // Set the view tree owners before setting the content view so that the inflation process // and attach listeners will see them already present ViewTreeLifecycleOwner.set(getWindow().getDecorView(), this); ViewTreeViewModelStoreOwner.set(getWindow().getDecorView(), this); ViewTreeSavedStateRegistryOwner.set(getWindow().getDecorView(), this); ViewTreeOnBackPressedDispatcherOwner.set(getWindow().getDecorView(), this); }
DialogFragment
1 2 3 4 5 6 7 8 9 10 11 12 13
publicvoidonStart() { super.onStart();
if (mDialog != null) { mViewDestroyed = false; mDialog.show(); // Only after we show does the dialog window actually return a decor view. ViewdecorView= mDialog.getWindow().getDecorView(); ViewTreeLifecycleOwner.set(decorView, this); ViewTreeViewModelStoreOwner.set(decorView, this); ViewTreeSavedStateRegistryOwner.set(decorView, this); } }
voidperformCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { mChildFragmentManager.noteStateNotSaved(); mPerformedCreateView = true; mViewLifecycleOwner = newFragmentViewLifecycleOwner(this, getViewModelStore()); mView = onCreateView(inflater, container, savedInstanceState); if (mView != null) { // Initialize the view lifecycle mViewLifecycleOwner.initialize(); // Tell the fragment's new view about it before we tell anyone listening // to mViewLifecycleOwnerLiveData and before onViewCreated, so that calls to // ViewTree get() methods return something meaningful ViewTreeLifecycleOwner.set(mView, mViewLifecycleOwner); ViewTreeViewModelStoreOwner.set(mView, mViewLifecycleOwner); ViewTreeSavedStateRegistryOwner.set(mView, mViewLifecycleOwner); // Then inform any Observers of the new LifecycleOwner mViewLifecycleOwnerLiveData.setValue(mViewLifecycleOwner); } else { if (mViewLifecycleOwner.isInitialized()) { thrownewIllegalStateException("Called getViewLifecycleOwner() but " + "onCreateView() returned null"); } mViewLifecycleOwner = null; } }