Lifecycle 生命周期源码解析

目录:

  1. 什么生命周期
  2. 什么是生命周期感知型组件
  3. Activity是如何把生命周期传给生命周期感知组件的

生命周期

安卓Activity或者Fragment的生命周期是从页面创建到销毁的一个过程

state.jpg

生命周期感知型组件

生命周期感知型组件,是可以在Activity或者Fragment生命周期变化的时候收到通知,进而在生命周期发生变化的时候处理相关逻辑, 比如广播的注册和解绑

那么如何创建一个生命周期感知型组件呢,首选需要创建一个类继承于LifecycleObserver,然后在处理生命周期的方法上写上Lifecycle的注解,这里的LifecycleObserver是一个空的interface; 然后在我们实现了了LifecycleOwner接口的Acitivy中, 使用 getLifecycle().addObserver(observer); 给observer赋予生命周期感知能力, 下面是实现代码

public class MyLifecycleObserver implements LifecycleObserver {
  
  @OnLifecycleEvent(Lifecycle.Event.ON_RESUME)
  public void onResume() {
    //在onResume的时候收到通知
    Log.d("test", "observer onResume" );
  }

  @OnLifecycleEvent(Lifecycle.Event.ON_PAUSE)
  public void onPause() {
    //在onPause的时候收到通知
    Log.d("test", "observer onPause");
  }
}

//MyActivity 的父类实现了LifecycleOwner 接口
class MyActivity extends AppCompatActivity {
  private MyLifecycleObserver observer = new MyLifecycleObserver();
  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    //
   getLifecycle().addObserver(observer);
  }  
}

Activity是如何把生命周期传给Observer的

上面提到了Activity通过getLifecycle().addObserver(observer)的方法就可以把生命周期传给observer, 那么下面说一下这个过程是如何工作的,下面的时序图描述了这个过程:

test.png

工作的开始我们找到了Activity的父类ComponentActivity ,生命周期的处理是从这个类开始的;父类ComponentActivity在onCreate的时候创建一个LifcycleRegistry 和一个ReportFragment,ReportFragment将生命周期传给LifecycleRegistry,由它处理生命周期的分发

  1. 创建LifecycleRegistry

    ComponentActivity在onCreate的时候就会创建一个LifecycleRegistry, 并将Acitivy自身传递给LifecycleRegistry持有,ComponentActivity实现了LifecycleOwner接口,实现它getLifecycle方法,返回一个Registry。

  2. 创建ReportFragment

    Fragment可以感知所在Activity的生命周期,这里创建了一个空的Fragment,用来感知Activity的生命周期,这种创建空Fragment的方法很常见,例如Glide的图片下载

  3. LifecycleRegistry 添加LifecycleObserver

    LifecycleRegistry调用addObserver(@NonNull LifecycleObserver observer)方法,将observer添加到map中, 这里看到并不是直接把observer对象存放到map中,而是创建了一个ObserverWithState

        @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);
            ....
        }
    

    ObserverWithState 有两个属性,State是个枚举

    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;
            }
        }
    
        public enum State {
            DESTROYED,
            INITIALIZED,
            CREATED,
            STARTED,
            public boolean isAtLeast(@NonNull State state) {
                return compareTo(state) >= 0;
            }
        }
    
  1. ReportFragment感知生命周期,将生命周期交给LifecycleRegistry处理

    我们看一下ReportFragment,ReportFragment收到onResume方法时,会调用自身的dispatch方法,把生命周期事件传给LifecycleRegistry

    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);
                }
            }
        }
    
  2. LifecycleRegistry处理生命周期

    LifecycleRegistry在handleLifecycleEvent(@NonNull Lifecycle.Event event)方法中,经历了moveToState()...sync()...forwardPass()

    public void handleLifecycleEvent(@NonNull Lifecycle.Event event) {
            State next = getStateAfter(event);
            moveToState(next);
        }
    //在forwardPass中,遍历保存observer的map,处理observer中的事件
     private void forwardPass(LifecycleOwner lifecycleOwner) {
            Iterator> ascendingIterator =
                    mObserverMap.iteratorWithAdditions();
            while (ascendingIterator.hasNext() && !mNewEventOccurred) {
                Entry 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();
                }
            }
        }
    

你可能感兴趣的:(Lifecycle 生命周期源码解析)