/** * Marks a class as a LifecycleObserver. It does not have any methods, instead, relies on * {@link OnLifecycleEvent} annotated methods. */ public interface LifecycleObserver {
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 ifthis State is greater or equal to the given {@code state}. * * @param state State to compare with * @return trueifthis State is greater or equal to the given {@code state} */ publicboolean isAtLeast(@NonNull State state) { return compareTo(state) >= 0; } } }
public interface LifecycleOwner { Lifecycle getLifecycle(); }
LifecycleOwner只提供一个getLifecycle()获取lifecycle对象。
在Activity/Fragment中,可以直接调用到getLifecycle()进行获取
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
public class FragmentActivity extends ComponentActivity implements ViewModelStoreOwner{ ... }
public class ComponentActivity extends Activity implements LifecycleOwner, KeyEventDispatcher.Component { ... private LifecycleRegistry mLifecycleRegistry = new LifecycleRegistry(this); ... @Override public Lifecycle getLifecycle() { return mLifecycleRegistry; } }
1 2 3 4 5 6 7 8 9 10
public class Fragment implements ComponentCallbacks, OnCreateContextMenuListener, LifecycleOwner, ViewModelStoreOwner { ... LifecycleRegistry mLifecycleRegistry = new LifecycleRegistry(this); ... @Override public Lifecycle getLifecycle() { return mLifecycleRegistry; } }
public class Fragment implements ComponentCallbacks, OnCreateContextMenuListener, LifecycleOwner, ViewModelStoreOwner { ... LifecycleRegistry mLifecycleRegistry = new LifecycleRegistry(this); ... @Override public Lifecycle getLifecycle() { return mLifecycleRegistry; }
public class ReportFragment extends Fragment { publicstaticvoid injectIfNeededIn(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(); } }
publicvoid handleLifecycleEvent(@NonNull Lifecycle.Event event) { //根据当前收到的生命周期状态获取事件发生后的后续状态 State next = getStateAfter(event); moveToState(next); }
privatevoid moveToState(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; } throw new 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 privatevoid sync() { 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; }
privatestatic Event downEvent(State state) { switch (state) { case INITIALIZED: throw new IllegalArgumentException(); case CREATED: return ON_DESTROY; case STARTED: return ON_STOP; case RESUMED: return ON_PAUSE; case DESTROYED: throw new IllegalArgumentException(); } throw new 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: throw new IllegalArgumentException(); } throw new IllegalArgumentException("Unexpected state value " + state); }