Lifecycle
is a class that holds the information about the lifecycle state of a component (like anactivity or a fragment) and allows other objects to observe this state.
Lifecycle
uses two main enumerations to track the lifecycle status for its associated component:
Event
The lifecycle events that are dispatched from the framework and the
Lifecycle
class. These events map to the callback events in activities and fragments.
State
The current state of the component tracked by the
Lifecycle
object.
Lifecycle是一个抽象类,持有组件(例如activity,fragment)生命周期状态的信息,允许其他objects观察这个生命周期状态;Lifecycle使用两个主要的枚举类跟踪与其有联系组件的生命周期状态:
Event:生命周期事件,从framework和Lifecycle.class分发生命周期事件
State:Lifecycle object跟踪的组件的当前状态
public abstract class Lifecycle { @MainThread public abstract void addObserver(@NonNull LifecycleObserver observer); //添加LifecycleObserver,当LifecycleOwner变化式,observer将会得到通知,例如当LifecycleOwner处于STARTED状态,observer将会收到ON_CREATE,ON_START事件
@MainThread public abstract void removeObserver(@NonNull LifecycleObserver observer);
@MainThread @NonNull public abstract State getCurrentState(); //返回当前Lifecycle状态 @SuppressWarnings("WeakerAccess") public enum Event { /** * Constant for onCreate event of the {@link LifecycleOwner}. */ ON_CREATE, // LifecycleOwner的onCreate事件常量 ON_START, // LifecycleOwner的onStart事件常量 ON_RESUME, // LifecycleOwner的onResume事件常量 ON_PAUSE, // LifecycleOwner的onPause事件常量 ON_STOP, // LifecycleOwner的onStop事件常量 ON_DESTROY, // LifecycleOwner的onDestroy事件常量 /** * 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. */
@SuppressWarnings("WeakerAccess") public enum State { DESTROYED, // LifecyleOwner的销毁状态,Lifecycle不再分发事件,举个栗子,当activity的onDestroy被调用之前会变成这个状态 INITIALIZED, // LifecycleOwner初始化状态,例如Activity,当被构造,但是还没有调用onCreate时的状态 CREATED, // LifecycleOwner被创建状态,例如Activity,在onCreate调用后,onStop调用前的状态 STARTED, // LifecycleOwner开始状态,例如Activity,在onStart调用后,onPause调用前的状态 RESUMED; // LifecycleOwner的resumed状态,例如Activity,在onResume调用后的状态
// 比较这个状态是否大于或等于给出的状态,如果大于或等于返回true
public boolean isAtLeast(@NonNull State state) { return compareTo(state) >= 0; } } }
LifecycleRegistry是Lifecycle的一个子类:Fragment和Support Activity拥有LifecycleRegistry,也可以在自定义的LifecycleOwner中直接使用LifecycleRegistry,它保存了LifecycleObserver的引用,当LifecycleOwner生命周期发生变化时通知LifecycleObserver
/** * An implementation of {@link 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. */ public class LifecycleRegistry extends Lifecycle { private FastSafeIterableMap mObserverMap = new FastSafeIterableMap<>(); // 用来保存LifecycleObserver
private State mState; // 当前状态
private final WeakReference mLifecycleOwner; private ArrayList mParentStates = new ArrayList<>();
public LifecycleRegistry(@NonNull LifecycleOwner provider) { mLifecycleOwner = new WeakReference<>(provider); mState = INITIALIZED; }
// 设置当前状态并通知所有的LifecycleObservers public void handleLifecycleEvent(@NonNull Lifecycle.Event event) { State next = getStateAfter(event); moveToState(next); } private void 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; sync(); mHandlingEvent = false; } @Override public void addObserver(@NonNull LifecycleObserver observer) { State initialState = mState == DESTROYED ? DESTROYED : INITIALIZED; ObserverWithState statefulObserver = new ObserverWithState(observer, initialState); ObserverWithState previous = mObserverMap.putIfAbsent(observer, statefulObserver); if (previous != null) { return; } LifecycleOwner lifecycleOwner = mLifecycleOwner.get(); if (lifecycleOwner == null) { // it is null we should be destroyed. Fallback quickly return; } boolean isReentrance = mAddingObserverCounter != 0 || mHandlingEvent; State targetState = calculateTargetState(observer); mAddingObserverCounter++; while ((statefulObserver.mState.compareTo(targetState) < 0 && mObserverMap.contains(observer))) { pushParentState(statefulObserver.mState); statefulObserver.dispatchEvent(lifecycleOwner, upEvent(statefulObserver.mState)); popParentState(); // mState / subling may have been changed recalculate targetState = calculateTargetState(observer); } if (!isReentrance) { // we do sync only on the top level. sync(); } mAddingObserverCounter--; } @Override public void removeObserver(@NonNull LifecycleObserver observer) { mObserverMap.remove(observer); } @SuppressWarnings("WeakerAccess") public int getObserverCount() { return mObserverMap.size(); } @NonNull @Override public State getCurrentState() { return mState; } 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); } }