Defines an object that has an Android Lifecycle. Fragment and FragmentActivity classes implement LifecycleOwner interface which has the getLifecycle method to access the Lifecycle. You can also implement LifecycleOwner in your own classes.
Event#ON_CREATE, Event#ON_START, Event#ON_RESUME events in this class are dispatched after the LifecycleOwner‘s related method returns. Event#ON_PAUSE, Event#ON_STOP, Event#ON_DESTROY events in this class are dispatched before the LifecycleOwner‘s related method is called. For instance, Event#ON_START will be dispatched after onStart returns, Event#ON_STOP will be dispatched before onStop is called. This gives you certain guarantees on which state the owner is in.
If you use Java 8 Language, then observe events with DefaultLifecycleObserver. To include it you should add "androidx.lifecycle:lifecycle-common-java8:<version>" to your build.gradle file.
1 2 3 4 5 6
classTestObserverimplementsDefaultLifecycleObserver{ @Override publicvoidonCreate(LifecycleOwner owner){ // your code } }
If you use Java 7 Language, Lifecycle events are observed using annotations. Once Java 8 Language becomes mainstream on Android, annotations will be deprecated, so between DefaultLifecycleObserver and annotations, you must always prefer DefaultLifecycleObserver.
Observer methods can receive zero or one argument. If used, the first argument must be of type LifecycleOwner. Methods annotated with Event#ON_ANY can receive the second argument, which must be of type Event.
publicstaticvoidinjectIfNeededIn(Activity activity){ if (Build.VERSION.SDK_INT >= 29) { // On API 29+, we can register for the correct Lifecycle callbacks directly activity.registerActivityLifecycleCallbacks( new LifecycleCallbacks()); } // 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.FragmentManager manager = activity.getFragmentManager(); if (manager.findFragmentByTag(REPORT_FRAGMENT_TAG) == null) { manager.beginTransaction().add(new ReportFragment(), 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; }
在 ReportFragment 中调用这些生命周期方法来 dispatch 生命周期事件。
1 2 3 4 5 6 7 8
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); } }
if (activity instanceof LifecycleOwner) { Lifecycle lifecycle = ((LifecycleOwner) activity).getLifecycle(); if (lifecycle instanceof LifecycleRegistry) { ((LifecycleRegistry) lifecycle).handleLifecycleEvent(event); } } }
LifecycleRegistry#handleLifecycleEvent
1 2 3 4
publicvoidhandleLifecycleEvent(@NonNull Lifecycle.Event event){ State next = getStateAfter(event); moveToState(next); }
getStateAfter 获得 event 后的 state:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
static State getStateAfter(Event event){ switch (event) { case ON_CREATE: case ON_STOP: return CREATED; case ON_START: case ON_PAUSE: return STARTED; case ON_RESUME: return RESUMED; case ON_DESTROY: return DESTROYED; case ON_ANY: break; } thrownew IllegalArgumentException("Unexpected event value " + event); }
LifecycleRegistry#moveToState
1 2 3 4 5 6 7 8 9 10 11 12 13 14
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; }
// happens only on the top of stack (never in reentrance), // so it doesn't have to take in account parents privatevoidsync(){ LifecycleOwner lifecycleOwner = mLifecycleOwner.get(); if (lifecycleOwner == null) { thrownew IllegalStateException("LifecycleOwner of this LifecycleRegistry is already" + "garbage collected. It is too late to change lifecycle state."); } while (!isSynced()) { mNewEventOccurred = false; // no need to check eldest for nullability, because isSynced does it for us. if (mState.compareTo(mObserverMap.eldest().getValue().mState) < 0) { backwardPass(lifecycleOwner); } Entry<LifecycleObserver, ObserverWithState> newest = mObserverMap.newest(); if (!mNewEventOccurred && newest != null && mState.compareTo(newest.getValue().mState) > 0) { forwardPass(lifecycleOwner); } } mNewEventOccurred = false; }