概述 前面我们讲到了lifecycle是如何使用的,但是我们单单知道如何使用它还是不够的,我们需要知道它到底是如何绑定生命周期的。那么本篇我们就讲一下lifecycle的原理篇。
本篇基于Android 9.0源码进行分析,如有不同,注意sdk版本。
Lifecycle是什么? 官方文档是这么描述的,Lifecycle它是一个类,用来存储相关组件的生命周期状态,如Activity或者Fragment等。并且允许其他组件对这些状态进行观察。
我们先简单看一下Lifecycle这个类的源码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 public abstract class Lifecycle { @RestrictTo(RestrictTo.Scope.LIBRARY_GROUP) @NonNull AtomicReference<Object> mInternalScopeRef = new AtomicReference<>(); @MainThread public abstract void addObserver (@NonNull LifecycleObserver observer) ; @MainThread public abstract void removeObserver (@NonNull LifecycleObserver observer) ; @MainThread @NonNull public abstract State getCurrentState () ; @SuppressWarnings("WeakerAccess") public enum Event { ON_CREATE, ON_START, ON_RESUME, ON_PAUSE, ON_STOP, ON_DESTROY, ON_ANY } @SuppressWarnings("WeakerAccess") public enum State { DESTROYED, INITIALIZED, CREATED, STARTED, RESUMED; public boolean isAtLeast (@NonNull State state) { return compareTo(state) >= 0 ; } } }
从源码可以看出,Lifecycle主要是定义了2个枚举,一个是Event,它代表着Lifecycle分配的生命周期事件,并且它会映射到activity或者fragment的生命周期回调事件里。还有一个是State,它是指Lifecycle所处的生命周期状态。我们可以通过下图来了解State和Event的关系。
如何与Activity和Fragment建立联系? 我们知道一般来说我们的activity是继承于FragmentActivity的。那么FragmentActivity又是继承于ComponentActivity。那我们看一下ComponentActivity的源码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 @RestrictTo(LIBRARY_GROUP_PREFIX) public class ComponentActivity extends Activity implements LifecycleOwner , KeyEventDispatcher .Component { @SuppressWarnings("deprecation") private SimpleArrayMap<Class<? extends ExtraData>, ExtraData> mExtraDataMap = new SimpleArrayMap<>(); private LifecycleRegistry mLifecycleRegistry = new LifecycleRegistry(this ); @SuppressWarnings("deprecation") @RestrictTo(LIBRARY_GROUP_PREFIX) @Deprecated public void putExtraData (ExtraData extraData) { mExtraDataMap.put(extraData.getClass(), extraData); } @SuppressLint("RestrictedApi") @Override protected void onCreate (@Nullable Bundle savedInstanceState) { super .onCreate(savedInstanceState); ReportFragment.injectIfNeededIn(this ); } @CallSuper @Override protected void onSaveInstanceState (@NonNull Bundle outState) { mLifecycleRegistry.markState(Lifecycle.State.CREATED); super .onSaveInstanceState(outState); } @RestrictTo(LIBRARY_GROUP_PREFIX) @SuppressWarnings({"unchecked", "deprecation"}) @Deprecated public <T extends ExtraData> T getExtraData (Class<T> extraDataClass) { return (T) mExtraDataMap.get(extraDataClass); } @NonNull @Override public Lifecycle getLifecycle () { return mLifecycleRegistry; } ... }
我们可以看到ComponentActivity实现了LifecycleOwner的接口。并且定义了LifecycleRegistry。LifecycleRegistry是Lifecycle的实现类。具体逻辑我们就不看了,有兴趣可以自己关注下。
上述代码中我们可以看到在onSaveInstanceState方法中,我们通过markState把状态设置成Lifecycle.State.CREATED。那么为什么找不到设置其他状态的逻辑呢?我们可以发现在onCreate方法中有一个inject方法。我们进入此方法,哎,它就找到了。我们看下它的源码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 ... static void dispatch (@NonNull Activity activity, @NonNull Lifecycle.Event event) { if (activity instanceof LifecycleRegistryOwner) { ((LifecycleRegistryOwner) activity).getLifecycle().handleLifecycleEvent(event); return ; } if (activity instanceof LifecycleOwner) { Lifecycle lifecycle = ((LifecycleOwner) activity).getLifecycle(); if (lifecycle instanceof LifecycleRegistry) { ((LifecycleRegistry) lifecycle).handleLifecycleEvent(event); } } } @Override public void onActivityCreated (Bundle savedInstanceState) { super .onActivityCreated(savedInstanceState); dispatchCreate(mProcessListener); dispatch(Lifecycle.Event.ON_CREATE); } @Override public void onStart () { super .onStart(); dispatchStart(mProcessListener); dispatch(Lifecycle.Event.ON_START); } @Override public void onResume () { super .onResume(); dispatchResume(mProcessListener); dispatch(Lifecycle.Event.ON_RESUME); } @Override public void onPause () { super .onPause(); dispatch(Lifecycle.Event.ON_PAUSE); } @Override public void onStop () { super .onStop(); dispatch(Lifecycle.Event.ON_STOP); } @Override public void onDestroy () { super .onDestroy(); dispatch(Lifecycle.Event.ON_DESTROY); mProcessListener = null ; } private void dispatch (@NonNull Lifecycle.Event event) { if (Build.VERSION.SDK_INT < 29 ) { dispatch(getActivity(), event); } } ...
我们可以看到在对应的生命周期调用了dispatch方法,而在dispatch方法中又调用了一个多参的dispatch方法。在此方法中会判断activity是属于LifecycleRegistryOwner还是LifecycleRegistry。最终都会调到LifecycleRegistry的handleLifecycleEvent方法中去。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 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 ; return ; } mHandlingEvent = true ; 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); }
我们可以看到它是通过getStateAfter去获取event的状态,具体可以参考一下上面的时序图。而在moveToState方法中它又回调用sync方法:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 private void sync () { LifecycleOwner lifecycleOwner = mLifecycleOwner.get(); if (lifecycleOwner == null ) { throw new IllegalStateException("LifecycleOwner of this LifecycleRegistry is already" + "garbage collected. It is too late to change lifecycle state." ); } while (!isSynced()) { mNewEventOccurred = false ; 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 ; }
这里会通过mObserverMap的eldest和newest拿到的状态做对比,判断是向前还是向后。比如ON_CREATE=>ON_START是向前,ON_START=>ON_CREATE是向后。整体流程是差不多的。具体我们看代码示例:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 private void forwardPass (LifecycleOwner lifecycleOwner) { Iterator<Entry<LifecycleObserver, ObserverWithState>> ascendingIterator = mObserverMap.iteratorWithAdditions(); while (ascendingIterator.hasNext() && !mNewEventOccurred) { Entry<LifecycleObserver, ObserverWithState> entry = ascendingIterator.next(); ObserverWithState observer = entry.getValue(); while ((observer.mState.compareTo(mState) < 0 && !mNewEventOccurred && mObserverMap.contains(entry.getKey()))) { pushParentState(observer.mState); observer.dispatchEvent(lifecycleOwner, upEvent(observer.mState)); popParentState(); } } } private void backwardPass (LifecycleOwner lifecycleOwner) { Iterator<Entry<LifecycleObserver, ObserverWithState>> descendingIterator = mObserverMap.descendingIterator(); while (descendingIterator.hasNext() && !mNewEventOccurred) { Entry<LifecycleObserver, ObserverWithState> entry = descendingIterator.next(); ObserverWithState observer = entry.getValue(); while ((observer.mState.compareTo(mState) > 0 && !mNewEventOccurred && mObserverMap.contains(entry.getKey()))) { Event event = downEvent(observer.mState); pushParentState(getStateAfter(event)); observer.dispatchEvent(lifecycleOwner, event); popParentState(); } } }
最终它都会走到 observer.dispatchEvent(lifecycleOwner, event);
方法中。 并且最终会调用 mLifecycleObserver.onStateChanged(owner, event);
也就是LifecycleEventObserver的方法。我们看基于LifecycleEventObserver的实现类ReflectiveGenericLifecycleObserver。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 class ReflectiveGenericLifecycleObserver implements LifecycleEventObserver { private final Object mWrapped; private final CallbackInfo mInfo; ReflectiveGenericLifecycleObserver(Object wrapped) { mWrapped = wrapped; mInfo = ClassesInfoCache.sInstance.getInfo(mWrapped.getClass()); } @Override public void onStateChanged (@NonNull LifecycleOwner source, @NonNull Event event) { mInfo.invokeCallbacks(source, event, mWrapped); } }
在onStateChanged方法中调用了CallbackInfo的invokeCallbacks方法:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 void invokeCallbacks (LifecycleOwner source, Lifecycle.Event event, Object target) { invokeMethodsForEvent(mEventToHandlers.get(event), source, event, target); invokeMethodsForEvent(mEventToHandlers.get(Lifecycle.Event.ON_ANY), source, event, target); } private static void invokeMethodsForEvent (List<MethodReference> handlers, LifecycleOwner source, Lifecycle.Event event, Object mWrapped) { if (handlers != null ) { for (int i = handlers.size() - 1 ; i >= 0 ; i--) { handlers.get(i).invokeCallback(source, event, mWrapped); } } } static class MethodReference { final int mCallType; final Method mMethod; MethodReference(int callType, Method method) { mCallType = callType; mMethod = method; mMethod.setAccessible(true ); } void invokeCallback (LifecycleOwner source, Lifecycle.Event event, Object target) { try { switch (mCallType) { case CALL_TYPE_NO_ARG: mMethod.invoke(target); break ; case CALL_TYPE_PROVIDER: mMethod.invoke(target, source); break ; case CALL_TYPE_PROVIDER_WITH_EVENT: mMethod.invoke(target, source, event); break ; } } catch (InvocationTargetException e) { throw new RuntimeException("Failed to call observer method" , e.getCause()); } catch (IllegalAccessException e) { throw new RuntimeException(e); } } ... } ...
最后走到的是MethodReference的invokeCallback方法,而MethodReference中有两个变量,一个是callType,它表示调用方法的类型,另一个是Method,表示方法,不管是哪种callType都会通过invoke对方法进行反射。
总结 最后我们以一张调用的时序图来对上述流程做个总结。
参考 官方文档