LifeCycle的作用是什么:生命周期感知型组件可执行操作来响应另一个组件(如 Activity 和 Fragment)的生命周期状态的变化。这些组件有助于您编写出更有条理且往往更精简的代码,此类代码更易于维护(摘自Android官网的解释)。 Lifecycle 最早是在 support 26.1.0 时被引入的,目前已经成为源码的一部分,而几乎无需使用者在 Gradle 额外地配置依赖。 Lifecycle的出现,可以帮助我们感知生命周期。

关于LifeCycle的使用这里不在复述直接看官方文档,本篇文章旨在理解Lifecycle的本质以及优秀代码的设计思想。

Lifecycle出现的背景原因

在LifeCycle没有出现之前,如果外部类要先监听Activity/Fragment的生命周期,需要定义个接口来监听Activity的生命周期方法(onCreate onStart onResume)等。避免内存泄漏等问题。
如下代码:随着Activity的功能越来越复杂,Listener处理的事情就会越来越多,最终导致代码难以维护。

  1. class MyLocationListener {
  2. public MyLocationListener(Context context, Callback callback) {
  3. // ...
  4. }
  5. void start() {
  6. // connect to system location service
  7. }
  8. void stop() {
  9. // disconnect from system location service
  10. }
  11. }
  12. class MyActivity extends AppCompatActivity {
  13. private MyLocationListener myLocationListener;
  14. @Override
  15. public void onCreate(...) {
  16. myLocationListener = new MyLocationListener(this, (location) -> {
  17. // update UI
  18. });
  19. }
  20. @Override
  21. public void onStart() {
  22. super.onStart();
  23. myLocationListener.start();
  24. // manage other components that need to respond
  25. // to the activity lifecycle
  26. }
  27. @Override
  28. public void onStop() {
  29. super.onStop();
  30. myLocationListener.stop();
  31. // manage other components that need to respond
  32. // to the activity lifecycle
  33. }
  34. }

那么Lifecycle是如何实现组件的隔离呢?

Lifecycle 实现隔离

在Android的官方文档中看到有两个关键的接口LifecycleOwner 表示该类具有LifecycleLifecycleObserver 监听生命周期事件 以及 [LifecycleRegistry](https://developer.android.com/reference/androidx/lifecycle/LifecycleRegistry?hl=zh-cn) 将生命周期事件转发
下面我们来自定义LifecycleOwner来实现Lifecycle的完整流转。
image.png

  1. open class LActivity:Activity(),LifecycleOwner {
  2. /**
  3. * 负责转发生命周期事件
  4. */
  5. private var mFragmentLifecycleRegistry = LifecycleRegistry(this)
  6. override fun onCreate(savedInstanceState: Bundle?) {
  7. super.onCreate(savedInstanceState)
  8. mFragmentLifecycleRegistry.handleLifecycleEvent(Lifecycle.Event.ON_CREATE)
  9. }
  10. override fun onStart() {
  11. super.onStart()
  12. mFragmentLifecycleRegistry.handleLifecycleEvent(Lifecycle.Event.ON_START)
  13. }
  14. override fun onResume() {
  15. super.onResume()
  16. mFragmentLifecycleRegistry.handleLifecycleEvent(Lifecycle.Event.ON_RESUME)
  17. }
  18. override fun onStop() {
  19. super.onStop()
  20. mFragmentLifecycleRegistry.handleLifecycleEvent(Lifecycle.Event.ON_STOP)
  21. }
  22. override fun onDestroy() {
  23. super.onDestroy()
  24. mFragmentLifecycleRegistry.handleLifecycleEvent(Lifecycle.Event.ON_DESTROY)
  25. }
  26. override fun getLifecycle(): Lifecycle {
  27. return mFragmentLifecycleRegistry
  28. }
  29. }

LifecycleEventObserver监听生命周期:

  1. class LifecycleActivity : LActivity() {
  2. override fun onCreate(savedInstanceState: Bundle?) {
  3. super.onCreate(savedInstanceState)
  4. setContentView(R.layout.activity_lifecycle)
  5. //感知生命周期
  6. lifecycle.addObserver(MyLifecycleObserver())
  7. }
  8. }
  9. /**
  10. * 监听生命周期
  11. */
  12. class MyLifecycleObserver:LifecycleEventObserver{
  13. override fun onStateChanged(source: LifecycleOwner, event: Lifecycle.Event) {
  14. Log.e("MyLifecycleObserver", "onStateChanged: ${source.lifecycle.currentState} event:${event}" )
  15. }
  16. }

运行结果如下:Lifecycle的事件以及状态的对应关系
image.png
在Android的官方文档 给出的事件和状态的关系,如下图和我们上述的是一致的。
事件是监听生命周期的而状态是判断页面是否处于激活状态。

ON_CREATE 和 ON_STOP 对应着CREATED。ON_START和ON_PAUSE对应着STARTED。这样的状态对应是因为ON_PAUSE有重走onStart的潜力,而ON_STOP有重走onCreate的潜力

image.png

那么Lifecycle为什么要设计事件和状态呢?

Lifecycle事件和状态的对应关系

  • event:实现了 LifecycleObserver 的第三方组件,能够在 onCreateonDestroy 等 event 方法内完成对生命周期的监听,event 是针对 第三方组件内部作为观察者,来观察 页面对组件的推送。
  • state :的存在,主要是 为了方便使用者判断 页面是否处于激活状态,以便实现生命周期安全的通知(在之前的一篇文章LiveData 如何安全观察数据,讲解了LiveData的核心代码和Lifecycle有关),state 是针对 页面作为观察者,来观察 来自第三方组件内部对页面的推送,那么此时通过 state 的判断,我们可确保在页面处于非激活状态时不收到 基于 LifeCycle 的组件(比如 LiveData)的推送。

LiveData是根据State来判断生命周期是否处于活跃状态的,如下代码:

  1. lifecycleOwner.lifecycle.currentState.isAtLeast(Lifecycle.State.STARTED)

只有 onResume 和 onPause 是介于 STARTED、RESUMED 状态之间,也即 只有这两个生命周期节点 100% 确定能收到 LiveData 的推送(FragmentActivity 额外支持 onStart 期间的接收)。(在重学安卓专栏中有介绍过状态的作用)

LifecycleRegistry 核心类

LifecycleRegistry 的设计如何去分发事件。其实看到源码可以和LiveData的分发消息差不多。

image.png
如下代码:通过handleLifecycleEvent发送生命周期事件

  1. // 分发生命周期事件
  2. public void handleLifecycleEvent(@NonNull Lifecycle.Event event) {
  3. enforceMainThreadIfNeeded("handleLifecycleEvent");
  4. moveToState(event.getTargetState());
  5. }
  6. private void moveToState(State next) {
  7. ......
  8. sync();
  9. ......
  10. }
  11. private void sync() {
  12. LifecycleOwner lifecycleOwner = mLifecycleOwner.get();
  13. ....
  14. while (!isSynced()) {
  15. mNewEventOccurred = false;
  16. if (mState.compareTo(mObserverMap.eldest().getValue().mState) < 0) {
  17. backwardPass(lifecycleOwner);
  18. }
  19. Map.Entry<LifecycleObserver, ObserverWithState> newest =
  20. mObserverMap.newest();
  21. if (!mNewEventOccurred && newest != null
  22. && mState.compareTo(newest.getValue().mState) > 0) {
  23. forwardPass(lifecycleOwner);
  24. }
  25. }
  26. mNewEventOccurred = false;
  27. }

sync()方法分别调用了forwardPassbackwardPass进行分发生命周期事件。
监听生命周期事件及状态:
mObserverMap存储监听ObserverWithState

  1. private FastSafeIterableMap<LifecycleObserver, ObserverWithState> mObserverMap =
  2. new FastSafeIterableMap<>();

addObserver添加监听事件,将obsever包装成ObserverWithState(这一段代码和LiveData中的observer类似)

  1. @Override
  2. public void addObserver(@NonNull LifecycleObserver observer) {
  3. enforceMainThreadIfNeeded("addObserver");
  4. State initialState = mState == DESTROYED ? DESTROYED : INITIALIZED;
  5. //observer 包装ObserverWithState
  6. ObserverWithState statefulObserver = new ObserverWithState(observer, initialState);
  7. //mObserverMap 存储statefulObserver
  8. ObserverWithState previous = mObserverMap.putIfAbsent(observer, statefulObserver);
  9. //.......
  10. boolean isReentrance = mAddingObserverCounter != 0 || mHandlingEvent;
  11. State targetState = calculateTargetState(observer);
  12. mAddingObserverCounter++;
  13. //重复addObserver 会返回之前的状态
  14. while ((statefulObserver.mState.compareTo(targetState) < 0
  15. && mObserverMap.contains(observer))) {
  16. pushParentState(statefulObserver.mState);
  17. final Event event = Event.upFrom(statefulObserver.mState);
  18. if (event == null) {
  19. throw new IllegalStateException("no event up from " + statefulObserver.mState);
  20. }
  21. //发送生命周期事件
  22. statefulObserver.dispatchEvent(lifecycleOwner, event);
  23. popParentState();
  24. // mState / subling may have been changed recalculate
  25. targetState = calculateTargetState(observer);
  26. }
  27. if (!isReentrance) {
  28. // we do sync only on the top level.
  29. sync();
  30. }
  31. mAddingObserverCounter--;
  32. }

ObserverWithState包装类通过dispatchEvent,在通过mLifecycleObserver.onStateChanged分发事件

  1. static class ObserverWithState {
  2. State mState;
  3. LifecycleEventObserver mLifecycleObserver;
  4. ObserverWithState(LifecycleObserver observer, State initialState) {
  5. mLifecycleObserver = Lifecycling.lifecycleEventObserver(observer);
  6. mState = initialState;
  7. }
  8. void dispatchEvent(LifecycleOwner owner, Event event) {
  9. //获取该事件对应的状态
  10. State newState = event.getTargetState();
  11. //判断当前的状态
  12. mState = min(mState, newState);
  13. //发送事件及状态
  14. mLifecycleObserver.onStateChanged(owner, event);
  15. mState = newState;
  16. }
  17. }