Lifecycle 源码解析 SafeIterableMap - 本质上是一个双链表伪装成的 Map,支持在遍历时候的修改(删除)操作
FastSafeIterableMap - 继承自 SafeIterableMap ,使用 HashMap 存取数据,速度更快,但同时占用内存也更大
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 40 41 42 43 enum Event { ON_CREATE, ON_START, ON_RESUME, ON_PAUSE, ON_STOP, ON_DESTROY, ON_ANY } ``` ```java enum State { DESTROYED, INITIALIZED, CRETED, STARTED, RESUMED; public boolean isAtLeast (@NonNull State state) { return compare(state) >= 0 ; } }
Event 是一种事件,是一种过程,好比是一条线段,State 是一个状态,好比是一个点。线段两端是点,两点之间是线段。 所以对于 Activity 来说,其生命周期状态和事件关系如下图:
Lifecycle 抽象类:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 abstract class Lifecycle { public abstract void addObserver (LifecycleObserver observer) ; public abstract void removeObserver (LifecycleObserver observer) ; public abstract State getCurrentState () ; }
LifecycleOwner 接口代表拥有生命周期的组件,例如 androidx.fragment.app.FragmentActivity,androidx.fragment.app.Fragment 都实现了该接口。当然也可以自己定义拥有生命周期的组件来作为 LifecyleOwner。
1 2 3 interface LifecycleOwner { Lifecycle getLifecycle () ; }
Lifecycle 是一个抽象类,其方法诸如 addObserver 等定义了方法规范,其实际实现类是 LifecycleRegistry。 该类可以处理多个观察者。
添加 Observer:
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 class LifecycleRegistry extends Lifecycle { private FastSafeIterableMap<LifecycleObserver, ObserverWithState> mObserverMap = new FastSafeIterableMap<>(); @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 ) { 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(); targetState = calculateTargetState(observer); } if (!isReentrance) { sync(); } mAddingObserverCounter--; } }
注释1,ObserverWithState 是 LifecycleRegistry 的静态内部类
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 static class ObserverWithState { State mState; LifecycleEventObserver mLifecycleObserver; ObserverWithState(LifecycleObserver observer, State initialState) { mLifecycleObserver = Lifecycling.lifecycleEventObserver(observer); mState = initialState; } } public interface LifecyeleEventObserver extends LifecycleObserver { void onStateChanged (LifecycleOwner source, Lifecycle.Event event) ; }
注释5:Lifecycling#lifecycleEventObserver 方法
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 static LifecycleEventObserver lifecycleEventObserver (Object object) { boolean isLifecycleEventObserver = object instanceof LifecycleEventObserver; boolean isFullLifecycleObserver = object instanceof FullLifecycleObserver; if (isLifecycleEventObserver && isFullLifecycleObserver) { return new FullLifecycleObserverAdapter((FullLifecycleObserver) object, (LifecycleEventObserver) object); } if (isFullLifecycleObserver) { return new FullLifecycleObserverAdapter((FullLifecycleObserver) object, null ); } if (isLifecycleEventObserver) { return (LifecycleEventObserver) object; } final Class<?> klass = object.getClass(); int type = getObserverConstructorType(klass); if (type == GENERATED_CALLBACK) { List<Constructor<? extends GeneratedAdapter>> constructors = sClassToAdapters.get(klass); if (constructors.size() == 1 ) { GeneratedAdapter generatedAdapter = createGeneratedAdapter( constructors.get(0 ), object); return new SingleGeneratedAdapterObserver(generatedAdapter); } GeneratedAdapter[] adapters = new GeneratedAdapter[constructors.size()]; for (int i = 0 ; i < constructors.size(); i++) { adapters[i] = createGeneratedAdapter(constructors.get(i), object); } return new CompositeGeneratedAdaptersObserver(adapters); } return new ReflectiveGenericLifecycleObserver(object); }
发送 Event 事件: 继承关系: AppCompatActivity -> FragmentActivity -> androidx.fragment.app.ComponentActivity
androidx.fragment.app.ComponentActivity#onCreate()
1 2 3 4 5 6 7 8 9 protected void onCreate (@Nullable Bundle savedInstanceState) { super .onCreate(savedInstanceState); mSavedStateRegistryController.performRestore(savedInstanceState); ReportFragment.injectIfNeededIn(this ); if (mContentLayoutId != 0 ) { setContentView(mContentLayoutId); } }
ReportFragment#injectIfNeededIn(this)
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 public class ReportFragment extends android .app .Fragment { public static void injectIfNeededIn (Activity activity) { if (Build.VERSION.SDK_INT >= 29 ) { activity.registerActivityLifecycleCallbacks( new LifecycleCallbacks()); } android.app.FragmentManager manager = activity.getFragmentManager(); if (manager.findFragmentByTag(REPORT_FRAGMENT_TAG) == null ) { manager.beginTransaction().add(new ReportFragment(), REPORT_FRAGMENT_TAG).commit(); manager.executePendingTransactions(); } } static class LifecycleCallbacks implements Application .ActivityLifecycleCallbacks { @Override public void onActivityPostCreated (@NonNull Activity activity, @Nullable Bundle savedInstanceState) { dispatch(activity, Lifecycle.Event.ON_CREATE); } } 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); } private void dispatch (@NonNull Lifecycle.Event event) { if (Build.VERSION.SDK_INT < 29 ) { dispatch(getActivity(), event); } } }
LifecycleRegistry#handleLifecycleEvent() 对 Lifecyle.Event 事件进行分发:
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 void handleLifecycleEvent (@NonNull Lifecycle.Event event) { State next = getStateAfter(event); moveToState(next); } 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); } private void moveToState (State next) { if (mState == next) { return ; } mState = next; if (mHandlingEvent || mAddingObserverCounter != 0 ) { mNewEventOccurred = true ; return ; } mHandlingEvent = true ; sync(); mHandlingEvent = false ; }
LifecycleRegistry#sync() 同步 Observer 队列的状态
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 68 69 70 71 72 73 74 75 76 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 ; } private boolean isSynced () { if (mObserverMap.size() == 0 ) { return true ; } State eldestObserverState = mObserverMap.eldest().getValue().mState; State newestObserverState = mObserverMap.newest().getValue().mState; return eldestObserverState == newestObserverState && mState == newestObserverState; } 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(); } } } 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(); } } }
ObserverWithState#dispatchEvent :
1 2 3 4 5 6 7 8 9 10 static class ObserverWithState { void dispatchEvent (LifecycleOwner owner, Event event) { State newState = getStateAfter(event); mState = min(mState, newState); mLifecycleObserver.onStateChanged(owner, event); mState = newState; } }
这里的 mLifecycleObserver 即我们之前分析的 Lifecycling.lifecycleEventObserver() 返回的 Observer