/** * Marks a class as a LifecycleObserver. It does not have any methods, instead, relies on * {@link OnLifecycleEvent} annotated methods. */ publicinterfaceLifecycleObserver{
publicenum Event { /** * Constant for onCreate event of the {@link LifecycleOwner}. */ ON_CREATE, /** * Constant for onStart event of the {@link LifecycleOwner}. */ ON_START, /** * Constant for onResume event of the {@link LifecycleOwner}. */ ON_RESUME, /** * Constant for onPause event of the {@link LifecycleOwner}. */ ON_PAUSE, /** * Constant for onStop event of the {@link LifecycleOwner}. */ ON_STOP, /** * Constant for onDestroy event of the {@link LifecycleOwner}. */ ON_DESTROY, /** * An {@link Event Event} constant that can be used to match all events. */ ON_ANY }
/** * Lifecycle states. You can consider the states as the nodes in a graph and * {@link Event}s as the edges between these nodes. */ publicenum State { /** * Destroyed state for a LifecycleOwner. After this event, this Lifecycle will not dispatch * any more events. For instance, for an {@link android.app.Activity}, this state is reached * <b>right before</b> Activity's {@link android.app.Activity#onDestroy() onDestroy} call. */ DESTROYED,
/** * Initialized state for a LifecycleOwner. For an {@link android.app.Activity}, this is * the state when it is constructed but has not received * {@link android.app.Activity#onCreate(android.os.Bundle) onCreate} yet. */ INITIALIZED,
/** * Created state for a LifecycleOwner. For an {@link android.app.Activity}, this state * is reached in two cases: * <ul> * <li>after {@link android.app.Activity#onCreate(android.os.Bundle) onCreate} call; * <li><b>right before</b> {@link android.app.Activity#onStop() onStop} call. * </ul> */ CREATED,
/** * Started state for a LifecycleOwner. For an {@link android.app.Activity}, this state * is reached in two cases: * <ul> * <li>after {@link android.app.Activity#onStart() onStart} call; * <li><b>right before</b> {@link android.app.Activity#onPause() onPause} call. * </ul> */ STARTED,
/** * Resumed state for a LifecycleOwner. For an {@link android.app.Activity}, this state * is reached after {@link android.app.Activity#onResume() onResume} is called. */ RESUMED;
/** * Compares if this State is greater or equal to the given {@code state}. * * @param state State to compare with * @return true if this State is greater or equal to the given {@code state} */ publicbooleanisAtLeast(@NonNull State state){ return compareTo(state) >= 0; } } }
publicclassReportFragmentextendsFragment{ publicstaticvoidinjectIfNeededIn(Activity activity){ // ProcessLifecycleOwner should always correctly work and some activities may not extend // FragmentActivity from support lib, so we use framework fragments for activities android.app.FragmentManager manager = activity.getFragmentManager(); //创建自身并加入宿主Activity 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(); } }
publicvoidhandleLifecycleEvent(@NonNull Lifecycle.Event event){ //根据当前收到的生命周期状态获取事件发生后的后续状态 State next = getStateAfter(event); moveToState(next); }
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; //执行同步方法,把所有的State转成Event sync(); mHandlingEvent = false; }
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); }
//Lifecycle自定义的数据结构,类似HashMap private FastSafeIterableMap<LifecycleObserver, ObserverWithState> mObserverMap = new FastSafeIterableMap<>();
// 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) { Log.w(LOG_TAG, "LifecycleOwner is garbage collected, you shouldn't try dispatch " + "new events from it."); return; } while (!isSynced()) { // mNewEventOccurred 是为了在 observer 触发状态变化时让 backwardPass/forwardPass() // 提前返回用的。我们刚准备调他们,这里设置为 false 即可。 mNewEventOccurred = false; // no need to check eldest for nullability, because isSynced does it for us. if (mState.compareTo(mObserverMap.eldest().getValue().mState) < 0) { // mObserverMap 里的元素的状态是非递增排列的,也就是说,队头的 state 最大 // 如果 mState 小于队列里最大的那个,说明有元素需要更新状态 // 为了维持 mObserverMap 的 Invariant,这里我们需要从队尾往前更新元素的状态 backwardPass(lifecycleOwner); } Entry<LifecycleObserver, ObserverWithState> newest = mObserverMap.newest(); // 如果 mNewEventOccurred,说明在上面调用 backwardPass() 时,客户触发了状态修改 if (!mNewEventOccurred && newest != null && mState.compareTo(newest.getValue().mState) > 0) { forwardPass(lifecycleOwner); } } mNewEventOccurred = false; }
// 如果所有的 observer 的状态都已经同步完,则返回 true privatebooleanisSynced(){ if (mObserverMap.size() == 0) { returntrue; } //获取最大状态 State eldestObserverState = mObserverMap.eldest().getValue().mState; //获取最小状态 State newestObserverState = mObserverMap.newest().getValue().mState; // 因为我们保证队头的 state >= 后面的元素的 state,所以只要判断头尾就够了 return eldestObserverState == newestObserverState && mState == newestObserverState; }
privatestatic Event downEvent(State state){ switch (state) { case INITIALIZED: thrownew IllegalArgumentException(); case CREATED: return ON_DESTROY; case STARTED: return ON_STOP; case RESUMED: return ON_PAUSE; case DESTROYED: thrownew IllegalArgumentException(); } thrownew IllegalArgumentException("Unexpected state value " + state); }
privatestatic Event upEvent(State state){ switch (state) { case INITIALIZED: case DESTROYED: return ON_CREATE; case CREATED: return ON_START; case STARTED: return ON_RESUME; case RESUMED: thrownew IllegalArgumentException(); } thrownew IllegalArgumentException("Unexpected state value " + state); }