提纲
- 什么是Lifecycle
- 如何使用 Lifecycle 观察宿主状态
- Fragment 是如何实现 Lifecycle 的
- Activity 是如何实现 Lifecycle 的
- Lifecycle 是如何分发宿状态的。
什么是 Lifecycle ?
Lifecycle 是具备宿主生命周期感知能力的组件。它能持有组件(如 Activity 或 Fragment)生命周期状态的信息,并且允许其他观察者监听宿主的状态。它也是 Jetpack 组件库的的核心基础,包括我们就后面会讲到的 LiveData , ViewModel 组件等也都是基于它来实现的。
使用 Lifecycle 前需要先添加依赖:
1 2 3 4
| api 'androidx.appcompat:appcompat:1.1.0' api 'androidx.lifecvcler:lifecycle-common:2.1.0'
|
Fragment 是如何实现 Lifecycle 的?
使用 Fragment 实现 Lifecycle 需要在各个生命周期方法内利用LifecycleRegistry分发相应的事件给每个观察者,以实现生命周期观察的能力:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
| public class Fragment implements LifecycleOwner { LifecycleRegistry mLifecycleRegistry = new LifecycleRegistry(this); @Override public Lifecycle getLifecycle() { return mLifecycleRegistry; }
void performCreate(){ mLifecycleRegistry.handleLifecycleEvent(Lifecycle.Event.ON_CREATE); }
void performStart(){ mLifecycleRegistry.handleLifecycleEvent(Lifecycle.Event.ON_START); } ..... void performResume(){ mLifecycleRegistry.handleLifecycleEvent(Lifecycle.Event.ON_RESUME); } }
|
LifecycleOwner、Lifecycle、LifecycleRegistry 的关系
事件在分发宿主生命周期事件的流程中涉及到三个类,我们分别来捋一捋:
- LifecycleOwner:我们的
Activity/Fragment
都实现了该接口,用以声明它是一个能够提供生命周期事件的宿主。同时必须复写getLifecycle()方法
提供一个Lifecycle
对象;
- Lifecycle:是一个抽象类,里面定义了两个枚举
State
宿主的状态,Event
需要分发的事件的类型;
- LifecycleRegistry: 是
Lifecycle
的唯一实现类,主要用来负责注册 Observer,以及分发宿主状态事件给它们。
Activity是如何实现Lifecycle的?
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| public class ComponentActivity extends Activity implements LifecycleOwner{ private LifecycleRegistry mLifecycleRegistry = new LifecycleRegistry(this); @NonNull @Override public Lifecycle getLifecycle() { return mLifecycleRegistry; }
protected void onCreate(Bundle bundle) { super.onCreate(savedInstanceState); ReportFragment.injectIfNeededIn(this); }
|
ReportFragment 核心源码
这里的实现其实跟 Fragment 中的源码是一样的,在各个生命周期方法内利用 LifecycleRegistry 派发相应的 Lifecycle.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
| public class ReportFragment extends Fragment{ public static void injectIfNeededIn(Activity activity) { android.app.FragmentManager manager = activity.getFragmentManager(); if (manager.findFragmentByTag(REPORT_FRAGMENT_TAG) == null) { manager.beginTransaction().add(new ReportFragment(), REPORT_FRAGMENT_TAG).commit(); manager.executePendingTransactions(); } } @Override public void onStart() { super.onStart(); dispatch(Lifecycle.Event.ON_START); } @Override public void onResume() { super.onResume(); dispatch(Lifecycle.Event.ON_RESUME); } @Override public void onPause() { super.onPause(); dispatch(Lifecycle.Event.ON_PAUSE); } @Override public void onDestroy() { super.onDestroy(); dispatch(Lifecycle.Event.ON_DESTROY); } private void dispatch(Lifecycle.Event event) { Lifecycle lifecycle = activity.getLifecycle(); if (lifecycle instanceof LifecycleRegistry) { ((LifecycleRegistry) lifecycle).handleLifecycleEvent(event); } }
|
宿主生命周期与宿主状态模型图
LifecycleRegistry 在分发事件的时候会涉及到两个概念:
- 宿主生命周期:就是我们烂熟于心的
oncreate,onstart onresume onpause onstop....
;
- 宿主的状态 :这个意思是指宿主执行了上述方法后,它所处的生命状态
从下面这张图不难看出宿主生命周期与宿主状态的对应关系分别为onCreate-Created、onStart-Started、onResume-Resumed、onpause-Started、onStop-Created、onDestroy-Destroyed,这里不用全部记住有个印象即可。
添加 observer 时,完整的生命周期事件分发
基于 Lifecycle 的特性我们在任意生命周期方法内注册观察者都能接收到完成的生命周期事件,比如在onResume 中注册一个观察者,它会依次收到:
LifecycleEvent.onCreate -> LifecycleEvent.onStart -> LifecycleEvent.onResume
添加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
| **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; }
State targetState = calculateTargetState(observer); while ((statefulObserver.mState.compareTo(targetState) < 0 && mObserverMap.contains(observer))) { pushParentState(statefulObserver.mState); statefulObserver.dispatchEvent(lifecycleOwner, upEvent(statefulObserver.mState)); targetState = calculateTargetState(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
| public void handleLifecycleEvent(@NonNull Lifecycle.Event event){ State next = getStateAfter(event); moveToState(next); } private void sync() { while (!isSynced()) { 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); } } }
|
ObserverWithState:持有观察者及其状态的内部类
把传入的 LifecycleObserver 适配成 LifecycleEventObserver,目的是为了统一事件的分发形式。
持有观察者的状态,方便与宿主状态做比对同步:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
| static class ObserverWithState { State mState; LifecycleEventObserver mLifecycleObserver; ObserverWithState(LifecycleObserver observer, State initialState) { mLifecycleObserver = Lifecycling.lifecycleEventObserver(observer); mState = initialState; }
void dispatchEvent(LifecycleOwner owner, Event event) { State newState = getStateAfter(event); mState = min(mState, newState); mLifecycleObserver.onStateChanged(owner, event); mState = newState; } }
|
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
| private static int resolveObserverCallbackType(Class<?> klass) { if (klass.getCanonicalName() == null) { return REFLECTIVE_CALLBACK; } Constructor<? extends GeneratedAdapter> constructor = generatedConstructor(klass); if (constructor != null) { sClassToAdapters.put(klass, Collections .<Constructor<? extends GeneratedAdapter>>singletonList(constructor)); return GENERATED_CALLBACK; } boolean hasLifecycleMethods = ClassesInfoCache.sInstance.hasLifecycleMethods(klass); if (hasLifecycleMethods) { return REFLECTIVE_CALLBACK; }
Class<?> superclass = klass.getSuperclass(); List<Constructor<? extends GeneratedAdapter>> adapterConstructors = null; if (isLifecycleParent(superclass)) { if (getObserverConstructorType(superclass) == REFLECTIVE_CALLBACK) { return REFLECTIVE_CALLBACK; } adapterConstructors = new ArrayList<>(sClassToAdapters.get(superclass)); }
for (Class<?> intrface : klass.getInterfaces()) { if (!isLifecycleParent(intrface)) { continue; } if (getObserverConstructorType(intrface) == REFLECTIVE_CALLBACK) { return REFLECTIVE_CALLBACK; } if (adapterConstructors == null) { adapterConstructors = new ArrayList<>(); } adapterConstructors.addAll(sClassToAdapters.get(intrface)); } if (adapterConstructors != null) { sClassToAdapters.put(klass, adapterConstructors); return GENERATED_CALLBACK; }
return REFLECTIVE_CALLBACK; }
|