生命周期事件管理利器 —— Lifecycle 原理详解

Lifecycle是什么

简单来说,Lifecycle是官方提供以方便管理声明周期事件的方式,给Activity、Fragment减肥。能把他们之中在生命周期变动时,需要做的各类事件抽离出来,集中到我们想的地方进行管理。

准备

添加依赖

dependencies {
   .....
    // 低版本SDK是compile
    implementation 'android.arch.lifecycle:extensions:1.1.1'
    annotationProcessor "android.arch.lifecycle:compiler:1.1.1"
    .....
}

添加仓库 (非必须,有些环境需要)

buildscript {
    
    repositories {
       ....
       //  官方提供,会被墙
        maven { url 'https://maven.google.com' }
      //  不能翻墙用这个
        maven { url 'https://dl.google.com/dl/android/maven2' }  
       ....
    }
}

案例

public class MyLife implements LifecycleObserver {

    private static final String TAG = "T-MyLife";

    @OnLifecycleEvent(Lifecycle.Event.ON_CREATE)
    void A(){
        Log.d(TAG, "create");
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_START)
    void B(){
        Log.d(TAG, "onStart");
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_RESUME)
    void C(){
        Log.d(TAG, "onResume");
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_PAUSE)
    void D(){
        Log.d(TAG, "Pause");
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_STOP)
    void E(){
        Log.d(TAG, "onStop");
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
    void F(){
        Log.d(TAG, "destroy");
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_ANY)
    void G(){
        Log.d(TAG, "Any");
    }
}

在Activity里进行注册

    MyLife life;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_b);

        life = new MyLife();
        getLifecycle().addObserver(life);
    }

日志,如下图


生命周期事件管理利器 —— Lifecycle 原理详解_第1张图片
生命周期.jpg

从日志中能看到,各生命周期变动时相应的被标示的函数都获得了执行机会,并且ANY在任意生命周期变动时都会被执行。

注册过程

Marks a class as a LifecycleObserver. It does not have any methods, instead, relies on
{@link OnLifecycleEvent} annotated methods.
大意是令该类成为生命周期观察者,无需实现任何方法,周期事件的触发依赖于@OnLifecycleEvent注解

首先,要监听使命周期必须要实现LifecycleObserver以做观察者标识,其中没有任何方法,通过源码注解可以看到。

getLifecycle().addObserver(life);

观察者通过以上代码进行注册

当前位置
LifecycleRegistry.addObserver() 

// 初始化状态
State initialState = mState == DESTROYED ? DESTROYED : INITIALIZED;
// 装配观察者信息
ObserverWithState statefulObserver = new ObserverWithState(observer, initialState);
// 保存信息
ObserverWithState previous = mObserverMap.putIfAbsent(observer, statefulObserver);

这里可以先了解一下State,代码入下

  // 以下所说调用方法均指android.app.Activity
    public enum State {
       //此状态下,Lifecycle不会分发任何事件
        DESTROYED,
       //此状态下,说明走到onCreate()
        INITIALIZED,
       //此状态下,说明走到onCreate()之后,或onStop()之前
        CREATED,
       //此状态下,说明走到onStart()之后,或onPause()之前
        STARTED,
       //此状态下,说明走到onResume()之后
        RESUMED;
        }

简单来说,State用来标示被观察者所处于的生命状态

观察者信息的装配

当前位置 ObserverWithState
构造函数

public ObserverWithState(LifecycleObserver observer, State initialState) {
    //  装配观察者,获取回调对象
    mLifecycleObserver = Lifecycling.getCallback(observer);
    mState = initialState;
}

不解释

当前位置
LifecycleRegistry.addObserver()
-- ObserverWithState()
-- Lifecycling.getCallback()

代码如下图

生命周期事件管理利器 —— Lifecycle 原理详解_第2张图片
lifecycle 构造.jpg

从代码上看,getCallback()主要通过反射并根据type以及Constructor对象的具体情况返回了不同的GenericLifecycleObserver(通过搜索能看到的实现类有5个,自行验证)对象。这里要注意,用来做判断的Constructor,并不是从我们传来的object对象也就是MyLife提取的,而是通过加工MyLife生成了一个新的类——MyLife_LifecycleAdapter,然后进行提取。不难发现,这一切是在getObserverConstructorType()里完成的。

这里就要问,为什么要构成新的类,具体情况如何

当前位置
Lifecycling.getCallback()
-- getObserverConstructorType()
-- resolveObserverCallbackTyp()
-- generatedConstructor()

生命周期事件管理利器 —— Lifecycle 原理详解_第3张图片
1.jpg

可见,generatedConstructor()构造出了即将会被放在MyLife同路径下的类MyLife_LifecycleAdapter的构造信息

当前位置
Lifecycling.getCallback()
-- getObserverConstructorType()
-- resolveObserverCallbackTyp()

 private static int resolveObserverCallbackType(Class klass) {
    ....
        Constructor constructor = generatedConstructor(klass);
        if (constructor != null) {
            sClassToAdapters.put(klass, Collections
                    .>singletonList(constructor));
            // 此例中运行到此
            return GENERATED_CALLBACK;
        }
....
}

MyLife_LifecycleAdapter的构造信息被保存到了sClassToAdapters中,并在此函数中将type=GENERATED_CALLBACK信息传回getCallback()

在当前节点MyLife_LifecycleAdapter还没有被构造出来,不难猜测在其他节点会被构造,在这里忽略跟踪这个过程,直接看一眼MyLife_LifecycleAdapter具体情况

public class MyLife_LifecycleAdapter implements GeneratedAdapter {
  final MyLife mReceiver;

  MyLife_LifecycleAdapter(MyLife receiver) {
    this.mReceiver = receiver;
  }

  @Override
  public void callMethods(LifecycleOwner owner, Lifecycle.Event event, boolean onAny,
      MethodCallsLogger logger) {
    boolean hasLogger = logger != null;
    if (onAny) {
      if (!hasLogger || logger.approveCall("G", 1)) {
        mReceiver.G();
      }
      return;
    }
    if (event == Lifecycle.Event.ON_CREATE) {
      if (!hasLogger || logger.approveCall("A", 1)) {
        mReceiver.A();
      }
      return;
    }
    if (event == Lifecycle.Event.ON_START) {
      if (!hasLogger || logger.approveCall("B", 1)) {
        mReceiver.B();
      }
      return;
    }
    if (event == Lifecycle.Event.ON_RESUME) {
      if (!hasLogger || logger.approveCall("C", 1)) {
        mReceiver.C();
      }
      return;
    }
    if (event == Lifecycle.Event.ON_PAUSE) {
      if (!hasLogger || logger.approveCall("D", 1)) {
        mReceiver.D();
      }
      return;
    }
    if (event == Lifecycle.Event.ON_STOP) {
      if (!hasLogger || logger.approveCall("E", 1)) {
        mReceiver.E();
      }
      return;
    }
    if (event == Lifecycle.Event.ON_DESTROY) {
      if (!hasLogger || logger.approveCall("F", 1)) {
        mReceiver.F();
      }
      return;
    }
  }
}

仅有方法callMethods(),以及我们的观察者MyLife的实例。以上代码告知信息如下
-Lifecycle框架为我们适配了MyLife,以符合使用标准,实际是会通过适配类去触发调用此例中的的生命周期观察者MyLife
-被@OnLifecycleEvent的函数最终被解析如生成的适配类中,并根据Event情况触发

插播一下Event

    public enum Event {
        ON_CREATE,
        ON_START,
        ON_RESUME,
        ON_PAUSE,
        ON_STOP,
        ON_DESTROY,
        ON_ANY
    }

用来标示观察者相应生命周期触发的事件,并据此被分配在生成的适配类中的相应位置

回到getCallback()
在我们的例子中,返回的是SingleGeneratedAdapterObserver,以下为完整代码

public class SingleGeneratedAdapterObserver implements GenericLifecycleObserver {

    private final GeneratedAdapter mGeneratedAdapter;

    SingleGeneratedAdapterObserver(GeneratedAdapter generatedAdapter) {
        mGeneratedAdapter = generatedAdapter;
    }

    @Override
    public void onStateChanged(LifecycleOwner source, Lifecycle.Event event) {
        mGeneratedAdapter.callMethods(source, event, false, null);
        mGeneratedAdapter.callMethods(source, event, true, null);
    }
}

可见,生成的适配类的实例被保存了下来。其他的GenericLifecycleObserver与此类似持有此信息

到这里,整个注册完毕,流程如下:

  • 调用LifecycleRegistry.addObserver()进行注册
  • ObserverWithState负责存储装配的信息
  • 初始化State
  • Lifecycling.getCallback()根据观察者情况生成了适配类,信息被GenericLifecycleObserver持有,且GenericLifecycleObserver被ObserverWithState持有
  • 观察者于ObserverWithState绑定

触发阶段

public class SupportActivity extends Activity implements LifecycleOwner{
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // 注入
        ReportFragment.injectIfNeededIn(this);
    }
}

ReportFragment会被注入到SupportActivity中,在声明周期发生变更时,作为Fragment,ReportFragment会接收到讯息

ReportFragment部分代码
    @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);
        // just want to be sure that we won't leak reference to an activity
        mProcessListener = null;
    }

    private void dispatch(Lifecycle.Event event) {
        // 也就是SupportActivity
        Activity activity = getActivity();
        if (activity instanceof LifecycleRegistryOwner) {
            ((LifecycleRegistryOwner) activity).getLifecycle().handleLifecycleEvent(event);
            return;
        }

        if (activity instanceof LifecycleOwner) {
          // 也就是LifecycleRegistry
            Lifecycle lifecycle = ((LifecycleOwner) activity).getLifecycle();
            if (lifecycle instanceof LifecycleRegistry) {
                ((LifecycleRegistry) lifecycle).handleLifecycleEvent(event);
            }
        }
    }

在触发此Fragment的生命周期时,所有事件都会通过dispatch()触发,最终交由LifecycleRegistry处理

当前位置
LifecycleRegistry.handleLifecycleEvent()

    public void handleLifecycleEvent(@NonNull Lifecycle.Event event) {
       // 获取状态
        State next = getStateAfter(event);
       // 执行事件,并更新状态
        moveToState(next);
    }
当前位置
LifecycleRegistry. moveToState()
-sync()

    private void sync() {
        // 也就是SupportActiviy
        LifecycleOwner lifecycleOwner = mLifecycleOwner.get();
        if (lifecycleOwner == null) {
            Log.w(LOG_TAG, "LifecycleOwner is garbage collected, you shouldn't try dispatch "
                    + "new events from it.");
            return;
        }
        while (!isSynced()) {
            mNewEventOccurred = false;
            // no need to check eldest for nullability, because isSynced does it for us.
            if (mState.compareTo(mObserverMap.eldest().getValue().mState) < 0) {
                backwardPass(lifecycleOwner);
            }
            Entry newest = mObserverMap.newest();
            if (!mNewEventOccurred && newest != null
                    && mState.compareTo(newest.getValue().mState) > 0) {
                forwardPass(lifecycleOwner);
            }
        }
        mNewEventOccurred = false;
    }

主要看backwardPass(lifecycleOwner)和forwardPass(lifecycleOwner),代码类似,择其一

    private void backwardPass(LifecycleOwner lifecycleOwner) {
        Iterator> descendingIterator =
                mObserverMap.descendingIterator();
        while (descendingIterator.hasNext() && !mNewEventOccurred) {
            Entry entry = descendingIterator.next();
            // 获取到每一个注册时根据观察者装配的信息ObserverWithState
            ObserverWithState observer = entry.getValue();
            while ((observer.mState.compareTo(mState) > 0 && !mNewEventOccurred
                    && mObserverMap.contains(entry.getKey()))) {
                // 更新Event状态
                Event event = downEvent(observer.mState);
                pushParentState(getStateAfter(event));
                // 分发事件
                observer.dispatchEvent(lifecycleOwner, event);
                popParentState();
            }
        }
    }

直接看事件分发

当前位置
ObserverWithState.dispatchEvent()

void dispatchEvent(LifecycleOwner owner, Event event) {
    State newState = getStateAfter(event);
    // 状态校准
    mState = min(mState, newState);
    //  mLifecycleObserver在本例中是SingleGeneratedAdapterObserver,在观察者注册也就是LifecycleRegistry.addObserver时获得
    mLifecycleObserver.onStateChanged(owner, event);
    // 更新状态
    mState = newState;
        }

回看SingleGeneratedAdapterObserver

    @Override
    public void onStateChanged(LifecycleOwner source, Lifecycle.Event event) {
        mGeneratedAdapter.callMethods(source, event, false, null);
        mGeneratedAdapter.callMethods(source, event, true, null);
    }
}

mGeneratedAdapter是在ObserverWithState初始化时Lifecycling.getCallback()根据观察者生成的适配类MyLife_LifecycleAdapter,最后观察者的相应事件得以触发(MyLife_LifecycleAdapter的代码就不贴了,可以回去看)

其他

public interface GenericLifecycleObserver extends LifecycleObserver {
    /**
     * Called when a state transition event happens.
     *
     * @param source The source of the event
     * @param event The event
     */
    void onStateChanged(LifecycleOwner source, Lifecycle.Event event);
}

在这里注意一下,其实GenericLifecycleObserver也是一个LifecycleObserver,只不过是在职责上与真正的观察者有所别。GenericLifecycleObserver主要还是作为中转,对事件做一些自己的处理,才继续将事件传下去。实际上,完全可以通过实现GenericLifecycleObserver作为观察者去直接对Event自行处理,注册方法不变。从Lifecycling.getCallback()能看到,如果观察者属于GenericLifecycleObserver,是不会生成适配类的,就直接交由观察者自行处理了。这里就不实现了。

生命周期观察者事件触发总结

  • 注册时生成适配类
  • SupportActivity负责注入ReportFragment
  • ReportFragment获得周期事件时,通过SupportActivity、LifecycleRegistry、ObserverWithState层层通知,最终告知生成的适配类:“是时候表演真正的技术了”
  • 观察者事件被触发

简单原理图(观察者不为GenericLifecycleObserver)


生命周期事件管理利器 —— Lifecycle 原理详解_第4张图片
原理图-3.png

元素职责标示

整个分析过程中涉及到的类和接口如下:

  • SupportActivity :持有LifecycleRegistry并负责注入ReportFragment

  • LifecycleOwner :标示被观察者

  • ReportFragment : 传递生命周期事件讯息,为出发点

  • LifecycleRegistry : 持有观察者、被观察者等信息

  • Event : 标示观察者事件触发时机

  • ObserverWithState : 持有state和适配类的信息

  • Lifecycing : 适配观察者,生成适配类,获取合适的GenericLifecycleObserver

  • GeneratedAdapter: 标示适配类,以供调用

  • GenericLifecycleObserver :传递生命周期事件讯息,中转点

  • State : 标示被观察者生命周期阶段


进阶:可被感知的数据 - LiveData 原理详解

你可能感兴趣的:(生命周期事件管理利器 —— Lifecycle 原理详解)