参考文章: 
https://mp.weixin.qq.com/s/VJif0D5PlrmyA1_emV-k0g  https://mp.weixin.qq.com/s/jU-UHkRbiruBq6BcNOjr5w

下面大量源码,请耐心点看~

什么是Lifecycle?

Lifecycle 组件指的是 android.arch.lifecycle 包下提供的各种类与接口,可以让开发者构建能感知其他组件(主要指Activity 、Fragment)生命周期(lifecycle-aware)的类。

为什么要引进Lifecycle?

前面说了,Lifecycle能够让开发者构建能感知其他组件(主要指Activity 、Fragment)生命周期(lifecycle-aware)的类。划重点,让开发者构建能感知其他组件(主要指Activity 、Fragment)生命周期(lifecycle-aware)的类。在android开发的过程中,我们常常需要让一些操作能够感知Activity/Fragment的生命周期,从而实现在活动状态下允许操作,而在销毁状态下需要自动禁止操作,释放资源,防止内存泄露。例如大名鼎鼎的图片加载框架Glide在Acticiy/Fragment处于前台的时候加载图片,而在不可见的状态下停止图片的加载,又例如我们希望RxJava的Disposable能够在Activity/Fragment销毁是自动dispose。Lifecycle的出现,让开发者们能够轻易地实现上述的功能。

一个用Lifecycle改造的MVP例子



比如我们现在需要实现这样一个功能:监听某个 Activity 生命周期的变化,在生命周期改变的时候打印日志。



  • 一般做法构造回调的方式

先定义基础IPresent接口:

public interface IPresent {

    void onCreate();
    void onStart();
    void onResume();
    void onPause();
    void onStop();
    void onDestory();
}复制代码
public interface IPresent {

    void onCreate();
    void onStart();
    void onResume();
    void onPause();
    void onStop();
    void onDestory();
}复制代码

然后在自定义的Present中继承IPresent接口:

public class MyPresent implements IPresent {

    private String TAG = "tag";

    @Override
    public void onCreate() {
        LogUtil.i(TAG, "onCreate");
    }

    @Override
    public void onStart() {
        LogUtil.i(TAG, "onStart");
    }

    @Override
    public void onResume() {
        LogUtil.i(TAG, "onResume");
    }

    @Override
    public void onPause() {
        LogUtil.i(TAG, "onPause");
    }

    @Override
    public void onStop() {
        LogUtil.i(TAG, "onStop");
    }

    @Override
    public void onDestory() {
        LogUtil.i(TAG, "onDestory");
    }复制代码
public class MyPresent implements IPresent {

    private String TAG = "tag";

    @Override
    public void onCreate() {
        LogUtil.i(TAG, "onCreate");
    }

    @Override
    public void onStart() {
        LogUtil.i(TAG, "onStart");
    }

    @Override
    public void onResume() {
        LogUtil.i(TAG, "onResume");
    }

    @Override
    public void onPause() {
        LogUtil.i(TAG, "onPause");
    }

    @Override
    public void onStop() {
        LogUtil.i(TAG, "onStop");
    }

    @Override
    public void onDestory() {
        LogUtil.i(TAG, "onDestory");
    }复制代码

最后在Activity依次调用回调方法分发事件:

public class MyActivity extends AppCompatActivity {

    protected MyPresent myPresent;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState, @Nullable PersistableBundle persistentState) {
        super.onCreate(savedInstanceState, persistentState);
        myPresent = new MyPresent();
        myPresent.onCreate();
    }

    @Override
    protected void onStart() {
        super.onStart();
        myPresent.onStart();
    }

    @Override
    protected void onResume() {
        super.onResume();
        myPresent.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
        myPresent.onPause();
    }

    @Override
    protected void onStop() {
        super.onStop();
        myPresent.onStop();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        myPresent.onDestory();
    }
}复制代码
public class MyActivity extends AppCompatActivity {

    protected MyPresent myPresent;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState, @Nullable PersistableBundle persistentState) {
        super.onCreate(savedInstanceState, persistentState);
        myPresent = new MyPresent();
        myPresent.onCreate();
    }

    @Override
    protected void onStart() {
        super.onStart();
        myPresent.onStart();
    }

    @Override
    protected void onResume() {
        super.onResume();
        myPresent.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
        myPresent.onPause();
    }

    @Override
    protected void onStop() {
        super.onStop();
        myPresent.onStop();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        myPresent.onDestory();
    }
}复制代码

通过这么一个简单的例子,我们可以看出,实现流程虽然很简单,但是代码实现繁琐,不够灵活,且代码侵入性太强。该例子只是展示了Present监听Activity生命周期,如果说还有类1,类2,类3......想要监听Activity的生命周期,那么就要在Activity的回调中添加对类1,类2,类3.....的回调。这就引起了一个思考,我们是否能够实现Activity在生命周期发生变化时主动通知需求方的功能呢?可以的,答案就是Lifecycle。

  • Lifecycle实现Present

先实现MyPresent,同时在每一个方法实现上增加@OnLifecycleEvent(Lifecycle.Event.XXXX)注解,OnLifecycleEvent对应了Activity的生命周期方法:

public class MyPresent implements IPresent, LifecycleObserver {

    @OnLifecycleEvent(Lifecycle.Event.ON_CREATE)
    @Override
    public void onCreate() {
        LogUtil.i(TAG, "onCreate");
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_START)
    @Override
    public void onStart() {
        LogUtil.i(TAG, "onStart");
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_RESUME)
    @Override
    public void onResume() {
        LogUtil.i(TAG, "onResume");
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_PAUSE)
    @Override
    public void onPause() {
        LogUtil.i(TAG, "onPause");
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_STOP)
    @Override
    public void onStop() {
        LogUtil.i(TAG, "onStop");
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
    @Override
    public void onDestory() {
        LogUtil.i(TAG, "onDestory");
    }
}复制代码
public class MyPresent implements IPresent, LifecycleObserver {

    @OnLifecycleEvent(Lifecycle.Event.ON_CREATE)
    @Override
    public void onCreate() {
        LogUtil.i(TAG, "onCreate");
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_START)
    @Override
    public void onStart() {
        LogUtil.i(TAG, "onStart");
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_RESUME)
    @Override
    public void onResume() {
        LogUtil.i(TAG, "onResume");
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_PAUSE)
    @Override
    public void onPause() {
        LogUtil.i(TAG, "onPause");
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_STOP)
    @Override
    public void onStop() {
        LogUtil.i(TAG, "onStop");
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
    @Override
    public void onDestory() {
        LogUtil.i(TAG, "onDestory");
    }
}复制代码

然后在需要监听的 Activity 中注册:

public class MyActivity extends AppCompatActivity {

    protected MyPresent myPresent;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState, @Nullable PersistableBundle persistentState) {
        super.onCreate(savedInstanceState, persistentState);
        
        getLifecycle().addObserver(new MyPresent()); //添加监听对象
    }

}复制代码
public class MyActivity extends AppCompatActivity {

    protected MyPresent myPresent;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState, @Nullable PersistableBundle persistentState) {
        super.onCreate(savedInstanceState, persistentState);
        
        getLifecycle().addObserver(new MyPresent()); //添加监听对象
    }

}复制代码

运行如下:

com.cimu.lifecycle I/MyPresent : onCreate()
com.cimu.lifecycle I/MyPresent : onStart()
com.cimu.lifecycle I/MyPresent : onResume()
com.cimu.lifecycle I/MyPresent : onPause()
com.cimu.lifecycle I/MyPresent : onStop()
com.cimu.lifecycle I/MyPresent : onDestroy()复制代码
com.cimu.lifecycle I/MyPresent : onCreate()
com.cimu.lifecycle I/MyPresent : onStart()
com.cimu.lifecycle I/MyPresent : onResume()
com.cimu.lifecycle I/MyPresent : onPause()
com.cimu.lifecycle I/MyPresent : onStop()
com.cimu.lifecycle I/MyPresent : onDestroy()复制代码

是不是很简单,我们希望MyPresent感知监听Activity的生命周期,只需要在Activity中调用一句getLifecycle().addObserver(new MyPresent())就可以了。Lifecycle是怎样实现感知生命周期进而通知观察者的功能的呢?

进入源码分析了,前方大量眼花缭乱的代码~~~

                           


Lifecycle源码分析

首先需要知道三个关键的东西:

  • LifecycleOwner:生命周期的事件分发者,在 Activity/Fragment 他们的生命周期发生变化的时发出相应的 Event 给LifecycleRegistry。
  • LifecycleObserver:生命周期的观察者,通过注解将处理函数与希望监听的Event绑定,当相应的Event发生时,LifecycleRegistry会通知相应的函数进行处理。
  • LifecycleRegistry:控制中心。它负责控制state的转换、接受分发event事件。

LifeCycle的源码分析,我们分为两个步骤来分析:

  • 注册/注销监听流程
  • 生命周期分发流程


注册/注销监听流程源码分析

从上面的MVP例子,我们已经知道,注册只需要调用getLifecycle().addObserver(observer)即可,那么addObserver就可以作为源码分析的入口。

通过追踪,我们发现getLifecycle返回的是SupportActivity中的mLifecycleRegistry,类型为LifecycleRegistry:

public class SupportActivity extends Activity implements LifecycleOwner {

    ......

    private FastSafeIterableMap<LifecycleObserver, ObserverWithState> mObserverMap
                                                             = new FastSafeIterableMap<>();
    private LifecycleRegistry mLifecycleRegistry = new LifecycleRegistry(this);

    ......

    @Override
    public Lifecycle getLifecycle() {
        return mLifecycleRegistry;
    }

    ......
}复制代码
public class SupportActivity extends Activity implements LifecycleOwner {

    ......

    private FastSafeIterableMap<LifecycleObserver, ObserverWithState> mObserverMap
                                                             = new FastSafeIterableMap<>();
    private LifecycleRegistry mLifecycleRegistry = new LifecycleRegistry(this);

    ......

    @Override
    public Lifecycle getLifecycle() {
        return mLifecycleRegistry;
    }

    ......
}复制代码

那么addObserver实际上是调用了LifecycleRegistry的addObserver方法,我们来看一下这个方法:

@Override
public void addObserver(@NonNull LifecycleObserver observer) {
    State initialState = mState == DESTROYED ? DESTROYED : INITIALIZED;

    //将传进来的监听者observer封装成一个ObserverWithState
    ObserverWithState statefulObserver = new ObserverWithState(observer, initialState);
    //将封装好的ObserverWithState存入集合中
    ObserverWithState previous = mObserverMap.putIfAbsent(observer, statefulObserver);

    if (previous != null) {
        return;
    }
    LifecycleOwner lifecycleOwner = mLifecycleOwner.get();
    if (lifecycleOwner == null) {
        // it is null we should be destroyed. Fallback quickly
        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();
        // 我们 dispatch 了一个事件给观察者,在回调观察者代码的时候,观察者可能会
        // 修改我们的状态
        // mState / subling may have been changed recalculate
        targetState = calculateTargetState(observer);
    }

    if (!isReentrance) {
        // we do sync only on the top level.
        sync();
    }
    mAddingObserverCounter--;
}复制代码
@Override
public void addObserver(@NonNull LifecycleObserver observer) {
    State initialState = mState == DESTROYED ? DESTROYED : INITIALIZED;

    //将传进来的监听者observer封装成一个ObserverWithState
    ObserverWithState statefulObserver = new ObserverWithState(observer, initialState);
    //将封装好的ObserverWithState存入集合中
    ObserverWithState previous = mObserverMap.putIfAbsent(observer, statefulObserver);

    if (previous != null) {
        return;
    }
    LifecycleOwner lifecycleOwner = mLifecycleOwner.get();
    if (lifecycleOwner == null) {
        // it is null we should be destroyed. Fallback quickly
        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();
        // 我们 dispatch 了一个事件给观察者,在回调观察者代码的时候,观察者可能会
        // 修改我们的状态
        // mState / subling may have been changed recalculate
        targetState = calculateTargetState(observer);
    }

    if (!isReentrance) {
        // we do sync only on the top level.
        sync();
    }
    mAddingObserverCounter--;
}复制代码

关于注册流程,上面我们重点关注封装了observer的ObserverWithState:

static class ObserverWithState {
    State mState;
    GenericLifecycleObserver mLifecycleObserver;

    ObserverWithState(LifecycleObserver observer, State initialState) {
        //getCallback()通过不同的类型的observer返回不同GenericLifecycleObserver实现类
        mLifecycleObserver = Lifecycling.getCallback(observer);
        mState = initialState;
    }

    //生命周期event的分发,最终会调用到这个方法,这个方法中在调用了GenericLifecycleObserver的
    //的onStateChanged方法
    void dispatchEvent(LifecycleOwner owner, Event event) {
        State newState = getStateAfter(event);
        mState = min(mState, newState);
        mLifecycleObserver.onStateChanged(owner, event);
        mState = newState;
    }
}复制代码
static class ObserverWithState {
    State mState;
    GenericLifecycleObserver mLifecycleObserver;

    ObserverWithState(LifecycleObserver observer, State initialState) {
        //getCallback()通过不同的类型的observer返回不同GenericLifecycleObserver实现类
        mLifecycleObserver = Lifecycling.getCallback(observer);
        mState = initialState;
    }

    //生命周期event的分发,最终会调用到这个方法,这个方法中在调用了GenericLifecycleObserver的
    //的onStateChanged方法
    void dispatchEvent(LifecycleOwner owner, Event event) {
        State newState = getStateAfter(event);
        mState = min(mState, newState);
        mLifecycleObserver.onStateChanged(owner, event);
        mState = newState;
    }
}复制代码
public interface GenericLifecycleObserver extends LifecycleObserver {
    void onStateChanged(LifecycleOwner source, Lifecycle.Event event);
}复制代码
public interface GenericLifecycleObserver extends LifecycleObserver {
    void onStateChanged(LifecycleOwner source, Lifecycle.Event event);
}复制代码

ObserverWithState的构造方法调用了Lifecycling.getCallback()将传入的observer进行解析,生成了对接口类GenericLifecycleObserver的具体实现返回,并且在具体实现类中重写了onStateChanged方法,在onStateChanged实现了生命周期的分发。当Activity/Fragment的生命周期发生变化时,会遍历LifecycleRegistry中的mObserverMap集合,取出其中的ObserverWithState节点,调用它的onStateChanged方法,而在ObserverWithState的onStateChanged的方法中又调用了实现了具体生命周期分发的GenericLifecycleObserver.onStateChanged方法。

在分析Lifecycling.getCallback()方法之前,我们先来看一下Lifecycle使用的三种基本使用方式:

  • 第一种使用方式。使用@onLifecycleEvent注解。注解处理器会将该注解解析并动态生成GeneratedAdapter代码,这个GeneratedAdapter会把对应的 Lifecycle.Event 封装为方法调用。最终通过GenericLifecycleObserver的onStateChanged方法调用生成的GeneratedAdapter的callMechods方法进行事件分发(结合下面例子理解)。
public class MyLifeCycleObserver implements LifeCycleObserver {

    @onLifecycleEvent(LifeCycle.Event.ON_CREATE)
    public onCreate(LifeCycleOwner owner) {
         //doSomething
    }
    
    @onLifecycleEvent(LifeCycle.Event.ON_DESTROY)
    public onDestroy(LifeCycleOwner owner) {
        //doSomething
    }
}

public class MainActivity extends AppCompatActivity {

    @override
    public void onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        getLifecycle().addObserver(new MyLifeCycleObserver());
    }
}
复制代码
public class MyLifeCycleObserver implements LifeCycleObserver {

    @onLifecycleEvent(LifeCycle.Event.ON_CREATE)
    public onCreate(LifeCycleOwner owner) {
         //doSomething
    }
    
    @onLifecycleEvent(LifeCycle.Event.ON_DESTROY)
    public onDestroy(LifeCycleOwner owner) {
        //doSomething
    }
}

public class MainActivity extends AppCompatActivity {

    @override
    public void onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        getLifecycle().addObserver(new MyLifeCycleObserver());
    }
}
复制代码

上述的例子中的MyLifeCycleObserver将会在编译时,生成GeneratedAdapter代码如下:

public class MyLifeCycleObserver_LifecycleAdapter implements GeneratedAdapter {

    final MyLifeCycleObserver mReceiver;

    MyLifeCycleObserver_LifecycleAdapter(MyLifeCycleObserver receiver) {
        //mReceiver就是我们开发者传入的MyLifeCycleObserver 
        this.mReceiver = receiver;
    }

    //callMechod方法会被GenericLifecycleObserver的onStateChanged方法调用,用以分发生命周期
    @Override
    public void callMethods(LifecycleOwner owner, Lifecycle.Event event, boolean onAny, MethodCallsLogger logger) {
        boolean hasLogger = logger != null;
        if (onAny) {
            return;
        }

        //如果生命周期事件是ON_CREATE,那么调用MyLifeCycleObserver的onCreate方法
        if (event == Lifecycle.Event.ON_CREATE) {
            if (!hasLogger || logger.approveCall("onCreate", 2)) {
                mReceiver.onCreate(owner);
            }
            return;
        }

        //如果生命周期事件是ON_DESTROY,那么调用MyLifeCycleObserver的onDestroy方法
        if (event == Lifecycle.Event.ON_DESTROY) {
            if (!hasLogger || logger.approveCall("onDestroy", 2)) {
                mReceiver.onDestroy(owner);
            }
            return;
        }
    }
}复制代码
public class MyLifeCycleObserver_LifecycleAdapter implements GeneratedAdapter {

    final MyLifeCycleObserver mReceiver;

    MyLifeCycleObserver_LifecycleAdapter(MyLifeCycleObserver receiver) {
        //mReceiver就是我们开发者传入的MyLifeCycleObserver 
        this.mReceiver = receiver;
    }

    //callMechod方法会被GenericLifecycleObserver的onStateChanged方法调用,用以分发生命周期
    @Override
    public void callMethods(LifecycleOwner owner, Lifecycle.Event event, boolean onAny, MethodCallsLogger logger) {
        boolean hasLogger = logger != null;
        if (onAny) {
            return;
        }

        //如果生命周期事件是ON_CREATE,那么调用MyLifeCycleObserver的onCreate方法
        if (event == Lifecycle.Event.ON_CREATE) {
            if (!hasLogger || logger.approveCall("onCreate", 2)) {
                mReceiver.onCreate(owner);
            }
            return;
        }

        //如果生命周期事件是ON_DESTROY,那么调用MyLifeCycleObserver的onDestroy方法
        if (event == Lifecycle.Event.ON_DESTROY) {
            if (!hasLogger || logger.approveCall("onDestroy", 2)) {
                mReceiver.onDestroy(owner);
            }
            return;
        }
    }
}复制代码
  • 第二种使用方式。直接继承GenericLifecycleObserver,并实现onStateChange方法
public class MyLifeCycleObserver extends GenericLifeCycleObserver {
    
    @override
    void onStateChanged(LifecycleOwner source, Lifecycle.Event event) {
        if(event == LifeCycleEvent.Event.ON_CREATE) {
            //dosomething
        } else if(event == LifeCycleEvent.Event.ON_DESTROY) {
            //doSomething
        }    
    }
}

public class MainActivity extends AppCompatActivity {

    @override
    public void onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        getLifecycle().addObserver(new MyLifeCycleObserver());
    }
}复制代码
public class MyLifeCycleObserver extends GenericLifeCycleObserver {
    
    @override
    void onStateChanged(LifecycleOwner source, Lifecycle.Event event) {
        if(event == LifeCycleEvent.Event.ON_CREATE) {
            //dosomething
        } else if(event == LifeCycleEvent.Event.ON_DESTROY) {
            //doSomething
        }    
    }
}

public class MainActivity extends AppCompatActivity {

    @override
    public void onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        getLifecycle().addObserver(new MyLifeCycleObserver());
    }
}复制代码
  • 第三种使用方式。继承DefaultLifecycleObserver接口(DefaultLifecycleObserver又继承自FullLifecycleObserver接口),并实现FullLifecycleObserver接口的onCreate、onStart、onResume、onPause、onStop、onDestroy等对应各自生命周期的方法
class MyLifycycleObserver implements DefaultLifecycleObserver {

    @Override
    public void onCreate(@NonNull LifecycleOwner owner) {
        //doSomething
    }

    ......

    @Override
    public void onDestroy(@NonNull LifecycleOwner owner) {
        //doSomething   
    }
}

public class MainActivity extends AppCompatActivity {

    @override
    public void onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        getLifecycle().addObserver(new MyLifeCycleObserver());
    }
}
复制代码
class MyLifycycleObserver implements DefaultLifecycleObserver {

    @Override
    public void onCreate(@NonNull LifecycleOwner owner) {
        //doSomething
    }

    ......

    @Override
    public void onDestroy(@NonNull LifecycleOwner owner) {
        //doSomething   
    }
}

public class MainActivity extends AppCompatActivity {

    @override
    public void onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        getLifecycle().addObserver(new MyLifeCycleObserver());
    }
}
复制代码

上面我们学习了使用Lifecycle的三种基本方法,下面我们简单看看Lifecycling.getCallback()方法是如何生成GenericLifecycleObserver具体实现类返回的:

//首先,我们先熟悉一下resolveObserverCallbackType这个方法,这个方法在Lifecycling.getCallback()
//中被调用,getCallback中会根据它的返回值决定返回什么类型的GenericLifecycleObserver实现类
private static int resolveObserverCallbackType(Class<?> klass) {
       
    if (klass.getCanonicalName() == null) {
        return REFLECTIVE_CALLBACK;
    }
    
    //当使用第一种方式注解时,会自动生成代码,生成的adapter继承了GeneratedAdapter,
    //所以返回值是GENERATED_CALLBACK
    Constructor<? extends GeneratedAdapter> constructor = generatedConstructor(klass);
    if (constructor != null) {
        sClassToAdapters.put(klass, Collections
                .<Constructor<? extends GeneratedAdapter>>singletonList(constructor));
        return GENERATED_CALLBACK;
    }

    //hasLifecycleMethods方法是判断klass中是否包含了onLifecycleEvent.class注解
    //如果包含,返回REFLECTIVE_CALLBACK
    boolean hasLifecycleMethods = ClassesInfoCache.sInstance.hasLifecycleMethods(klass);
    if (hasLifecycleMethods) {
        return REFLECTIVE_CALLBACK;
    }

    //递归调用resolveObserverCallbackType方法,遍历klass的父类
    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));
    }

    //遍历并且递归kclass的接口
    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;
}复制代码
//首先,我们先熟悉一下resolveObserverCallbackType这个方法,这个方法在Lifecycling.getCallback()
//中被调用,getCallback中会根据它的返回值决定返回什么类型的GenericLifecycleObserver实现类
private static int resolveObserverCallbackType(Class<?> klass) {
       
    if (klass.getCanonicalName() == null) {
        return REFLECTIVE_CALLBACK;
    }
    
    //当使用第一种方式注解时,会自动生成代码,生成的adapter继承了GeneratedAdapter,
    //所以返回值是GENERATED_CALLBACK
    Constructor<? extends GeneratedAdapter> constructor = generatedConstructor(klass);
    if (constructor != null) {
        sClassToAdapters.put(klass, Collections
                .<Constructor<? extends GeneratedAdapter>>singletonList(constructor));
        return GENERATED_CALLBACK;
    }

    //hasLifecycleMethods方法是判断klass中是否包含了onLifecycleEvent.class注解
    //如果包含,返回REFLECTIVE_CALLBACK
    boolean hasLifecycleMethods = ClassesInfoCache.sInstance.hasLifecycleMethods(klass);
    if (hasLifecycleMethods) {
        return REFLECTIVE_CALLBACK;
    }

    //递归调用resolveObserverCallbackType方法,遍历klass的父类
    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));
    }

    //遍历并且递归kclass的接口
    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;
}复制代码
//getCallBack的参数object是我们getLifeCycle().addObserver(observer)时传入的监听者observer
static GenericLifecycleObserver getCallback(Object object) {

    if (object instanceof FullLifecycleObserver) {
       //第三种使用方式,因为DefaultLifecycleObserver继承与FullLifecycleObserver
        return new FullLifecycleObserverAdapter((FullLifecycleObserver) object);
    }

    if (object instanceof GenericLifecycleObserver) {
        //第二种使用方式,当我们使用直接继承GenericLifecycleObserver这种方法时,直接返回
        return (GenericLifecycleObserver) object;
    }

    final Class<?> klass = object.getClass();
    //第一种使用方式,当使用注解时,getObserverConstructorType的返回值是GENERATED_CALLBACK
    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);
    }

    //当oberver都不符合上面几种类型时,会直接实例化ReflectiveGenericLifecycleObserver
    //作为替代返回(一般情况下,是不会走到这里的,可能是为了应对混淆机制而做的的一种安全模式)
    //在ReflectiveGenericLifecycleObserver中会找oberver中的onLifecyleEvent注解,并且将这些带注解
    //的方法生成MethodReference并添加到List<MethodReference>中,作为生命周期分发的调用方法
    return new ReflectiveGenericLifecycleObserver(object);
}复制代码
//getCallBack的参数object是我们getLifeCycle().addObserver(observer)时传入的监听者observer
static GenericLifecycleObserver getCallback(Object object) {

    if (object instanceof FullLifecycleObserver) {
       //第三种使用方式,因为DefaultLifecycleObserver继承与FullLifecycleObserver
        return new FullLifecycleObserverAdapter((FullLifecycleObserver) object);
    }

    if (object instanceof GenericLifecycleObserver) {
        //第二种使用方式,当我们使用直接继承GenericLifecycleObserver这种方法时,直接返回
        return (GenericLifecycleObserver) object;
    }

    final Class<?> klass = object.getClass();
    //第一种使用方式,当使用注解时,getObserverConstructorType的返回值是GENERATED_CALLBACK
    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);
    }

    //当oberver都不符合上面几种类型时,会直接实例化ReflectiveGenericLifecycleObserver
    //作为替代返回(一般情况下,是不会走到这里的,可能是为了应对混淆机制而做的的一种安全模式)
    //在ReflectiveGenericLifecycleObserver中会找oberver中的onLifecyleEvent注解,并且将这些带注解
    //的方法生成MethodReference并添加到List<MethodReference>中,作为生命周期分发的调用方法
    return new ReflectiveGenericLifecycleObserver(object);
}复制代码

好了,Lifecycling.getCallback()如果真的要详细的分析,篇幅会很大,在这里,我们粗略的分析了下。大家如果想深入了解,自己结合源码看是最好不过的。

总结一下注册的流程:

  1. Acitivty中调用LifecycleRegistry的addObserver,传入一个LifecycleObserver
  2. 传入的LifecycleObserver被封装成一个ObserverWithState存入集合中,当生命周期发生改变的时候,就会遍历这个ObserverWithState集合,并且调用ObserverWithState的dispatchEvent进行分发
  3. 在ObserverWithState构造方法中,调用了Lifecycling.getCallback(observer)生成了具体的 GenericLifecycleObserver对象返回。在ObserverWithState的dispatchEvent()方法中调用了GenericLifecycleObserver对象的onStateChanged方法进行事件分发


至于注销流程就很简单了,直接将observer从集合中remove,代码如下:

@Override
public void removeObserver(@NonNull LifecycleObserver observer) {
    // we consciously decided not to send destruction events here in opposition to addObserver.
    // Our reasons for that:
    // 1. These events haven't yet happened at all. In contrast to events in addObservers, that
    // actually occurred but earlier.
    // 2. There are cases when removeObserver happens as a consequence of some kind of fatal
    // event. If removeObserver method sends destruction events, then a clean up routine becomes
    // more cumbersome. More specific example of that is: your LifecycleObserver listens for
    // a web connection, in the usual routine in OnStop method you report to a server that a
    // session has just ended and you close the connection. Now let's assume now that you
    // lost an internet and as a result you removed this observer. If you get destruction
    // events in removeObserver, you should have a special case in your onStop method that
    // checks if your web connection died and you shouldn't try to report anything to a server.
    mObserverMap.remove(observer);
}复制代码
@Override
public void removeObserver(@NonNull LifecycleObserver observer) {
    // we consciously decided not to send destruction events here in opposition to addObserver.
    // Our reasons for that:
    // 1. These events haven't yet happened at all. In contrast to events in addObservers, that
    // actually occurred but earlier.
    // 2. There are cases when removeObserver happens as a consequence of some kind of fatal
    // event. If removeObserver method sends destruction events, then a clean up routine becomes
    // more cumbersome. More specific example of that is: your LifecycleObserver listens for
    // a web connection, in the usual routine in OnStop method you report to a server that a
    // session has just ended and you close the connection. Now let's assume now that you
    // lost an internet and as a result you removed this observer. If you get destruction
    // events in removeObserver, you should have a special case in your onStop method that
    // checks if your web connection died and you shouldn't try to report anything to a server.
    mObserverMap.remove(observer);
}复制代码


生命周期的分发流程

我们注册observer的时候,实际上是调用了SupportActivity中的mLifecycleRegistry对象的方法,那么我们分析下SupportActivity的onCreate方法:

@Override
@SuppressWarnings("RestrictedApi")
protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    ReportFragment.injectIfNeededIn(this);
}复制代码
@Override
@SuppressWarnings("RestrictedApi")
protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    ReportFragment.injectIfNeededIn(this);
}复制代码

在onCreate中调用了ReportFragment的injectIfNeedIn方法。这个方法其实就是往Activity中添加了一个Fragment。我们知道,Fragment是依附于Activity上的,Fragment的生命周期跟随Activity的生命周期。既然这个ReportFragment能够感知Activity的生命周期,那么它是不是就是负责将生命周期事件分发给LifecycleObserver的呢?

public class ReportFragment extends Fragment {
    private static final String REPORT_FRAGMENT_TAG = "android.arch.lifecycle"
            + ".LifecycleDispatcher.report_fragment_tag";

    public static void injectIfNeededIn(Activity activity) {
        // ProcessLifecycleOwner should always correctly work and some activities may not extend
        // FragmentActivity from support lib, so we use framework fragments for activities
        android.app.FragmentManager manager = activity.getFragmentManager();
        if (manager.findFragmentByTag(REPORT_FRAGMENT_TAG) == null) {
            manager.beginTransaction().add(new ReportFragment(), REPORT_FRAGMENT_TAG).commit();
            // Hopefully, we are the first to make a transaction.
            manager.executePendingTransactions();
        }
    }

    static ReportFragment get(Activity activity) {
        return (ReportFragment) activity.getFragmentManager().findFragmentByTag(
                REPORT_FRAGMENT_TAG);
    }

    private ActivityInitializationListener mProcessListener;

    private void dispatchCreate(ActivityInitializationListener listener) {
        if (listener != null) {
            listener.onCreate();
        }
    }

    private void dispatchStart(ActivityInitializationListener listener) {
        if (listener != null) {
            listener.onStart();
        }
    }

    private void dispatchResume(ActivityInitializationListener listener) {
        if (listener != null) {
            listener.onResume();
        }
    }

    @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) {
        Activity activity = getActivity();
        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);
            }
        }
    }

    void setProcessListener(ActivityInitializationListener processListener) {
        mProcessListener = processListener;
    }

    interface ActivityInitializationListener {
        void onCreate();

        void onStart();

        void onResume();
    }
}复制代码
public class ReportFragment extends Fragment {
    private static final String REPORT_FRAGMENT_TAG = "android.arch.lifecycle"
            + ".LifecycleDispatcher.report_fragment_tag";

    public static void injectIfNeededIn(Activity activity) {
        // ProcessLifecycleOwner should always correctly work and some activities may not extend
        // FragmentActivity from support lib, so we use framework fragments for activities
        android.app.FragmentManager manager = activity.getFragmentManager();
        if (manager.findFragmentByTag(REPORT_FRAGMENT_TAG) == null) {
            manager.beginTransaction().add(new ReportFragment(), REPORT_FRAGMENT_TAG).commit();
            // Hopefully, we are the first to make a transaction.
            manager.executePendingTransactions();
        }
    }

    static ReportFragment get(Activity activity) {
        return (ReportFragment) activity.getFragmentManager().findFragmentByTag(
                REPORT_FRAGMENT_TAG);
    }

    private ActivityInitializationListener mProcessListener;

    private void dispatchCreate(ActivityInitializationListener listener) {
        if (listener != null) {
            listener.onCreate();
        }
    }

    private void dispatchStart(ActivityInitializationListener listener) {
        if (listener != null) {
            listener.onStart();
        }
    }

    private void dispatchResume(ActivityInitializationListener listener) {
        if (listener != null) {
            listener.onResume();
        }
    }

    @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) {
        Activity activity = getActivity();
        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);
            }
        }
    }

    void setProcessListener(ActivityInitializationListener processListener) {
        mProcessListener = processListener;
    }

    interface ActivityInitializationListener {
        void onCreate();

        void onStart();

        void onResume();
    }
}复制代码

ReportFragment的代码很好理解,我们能够在代码里面发现Lifecycle.Event.xxx事件,并且在它的生命周期回调方法中将Lifecycle.Event.xxx事件传给了dispatch方法,很明显是用来分发生命周期的。在ReportFragment的dispatch方法中,调用了LifecycleRegistry的handleLifecycleEvent方法:

public void handleLifecycleEvent(@NonNull Lifecycle.Event event) {
    State next = getStateAfter(event);
    moveToState(next);
}复制代码
public void handleLifecycleEvent(@NonNull Lifecycle.Event event) {
    State next = getStateAfter(event);
    moveToState(next);
}复制代码

在分析这个方法之前,我们先要了解Lifecycle的事件与状态:

public abstract class Lifecycle {

    public enum Event {
        /**
         * Constant for onCreate event of the {@link LifecycleOwner}.
         */
        ON_CREATE,
        /**
         * Constant for onStart event of the {@link LifecycleOwner}.
         */
        ON_START,
        /**
         * Constant for onResume event of the {@link LifecycleOwner}.
         */
        ON_RESUME,
        /**
         * Constant for onPause event of the {@link LifecycleOwner}.
         */
        ON_PAUSE,
        /**
         * Constant for onStop event of the {@link LifecycleOwner}.
         */
        ON_STOP,
        /**
         * Constant for onDestroy event of the {@link LifecycleOwner}.
         */
        ON_DESTROY,
        /**
         * An {@link Event Event} constant that can be used to match all events.
         */
        ON_ANY
    }

    public enum State {
        /**
         * Destroyed state for a LifecycleOwner. After this event, this Lifecycle will not dispatch
         * any more events. For instance, for an {@link android.app.Activity}, this state is reached
         * <b>right before</b> Activity's {@link android.app.Activity#onDestroy() onDestroy} call.
         */
        DESTROYED,

        /**
         * Initialized state for a LifecycleOwner. For an {@link android.app.Activity}, this is
         * the state when it is constructed but has not received
         * {@link android.app.Activity#onCreate(android.os.Bundle) onCreate} yet.
         */
        INITIALIZED,

        /**
         * Created state for a LifecycleOwner. For an {@link android.app.Activity}, this state
         * is reached in two cases:
         * <ul>
         *     <li>after {@link android.app.Activity#onCreate(android.os.Bundle) onCreate} call;
         *     <li><b>right before</b> {@link android.app.Activity#onStop() onStop} call.
         * </ul>
         */
        CREATED,

        /**
         * Started state for a LifecycleOwner. For an {@link android.app.Activity}, this state
         * is reached in two cases:
         * <ul>
         *     <li>after {@link android.app.Activity#onStart() onStart} call;
         *     <li><b>right before</b> {@link android.app.Activity#onPause() onPause} call.
         * </ul>
         */
        STARTED,

        /**
         * Resumed state for a LifecycleOwner. For an {@link android.app.Activity}, this state
         * is reached after {@link android.app.Activity#onResume() onResume} is called.
         */
        RESUMED;
    }
}复制代码
public abstract class Lifecycle {

    public enum Event {
        /**
         * Constant for onCreate event of the {@link LifecycleOwner}.
         */
        ON_CREATE,
        /**
         * Constant for onStart event of the {@link LifecycleOwner}.
         */
        ON_START,
        /**
         * Constant for onResume event of the {@link LifecycleOwner}.
         */
        ON_RESUME,
        /**
         * Constant for onPause event of the {@link LifecycleOwner}.
         */
        ON_PAUSE,
        /**
         * Constant for onStop event of the {@link LifecycleOwner}.
         */
        ON_STOP,
        /**
         * Constant for onDestroy event of the {@link LifecycleOwner}.
         */
        ON_DESTROY,
        /**
         * An {@link Event Event} constant that can be used to match all events.
         */
        ON_ANY
    }

    public enum State {
        /**
         * Destroyed state for a LifecycleOwner. After this event, this Lifecycle will not dispatch
         * any more events. For instance, for an {@link android.app.Activity}, this state is reached
         * <b>right before</b> Activity's {@link android.app.Activity#onDestroy() onDestroy} call.
         */
        DESTROYED,

        /**
         * Initialized state for a LifecycleOwner. For an {@link android.app.Activity}, this is
         * the state when it is constructed but has not received
         * {@link android.app.Activity#onCreate(android.os.Bundle) onCreate} yet.
         */
        INITIALIZED,

        /**
         * Created state for a LifecycleOwner. For an {@link android.app.Activity}, this state
         * is reached in two cases:
         * <ul>
         *     <li>after {@link android.app.Activity#onCreate(android.os.Bundle) onCreate} call;
         *     <li><b>right before</b> {@link android.app.Activity#onStop() onStop} call.
         * </ul>
         */
        CREATED,

        /**
         * Started state for a LifecycleOwner. For an {@link android.app.Activity}, this state
         * is reached in two cases:
         * <ul>
         *     <li>after {@link android.app.Activity#onStart() onStart} call;
         *     <li><b>right before</b> {@link android.app.Activity#onPause() onPause} call.
         * </ul>
         */
        STARTED,

        /**
         * Resumed state for a LifecycleOwner. For an {@link android.app.Activity}, this state
         * is reached after {@link android.app.Activity#onResume() onResume} is called.
         */
        RESUMED;
    }
}复制代码

Lifecycle.Event对应activity的各个声明周期,Lifecycle.State则是Lifecycle的状态。在LifecycleRegistry 中定义了状态间的转化关系:

public class LifecycleRegistry extends Lifecycle {

    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 static Event downEvent(State state) {
        switch (state) {
            case INITIALIZED:
                throw new IllegalArgumentException();
            case CREATED:
                return ON_DESTROY;
            case STARTED:
                return ON_STOP;
            case RESUMED:
                return ON_PAUSE;
            case DESTROYED:
                throw new IllegalArgumentException();
        }
        throw new IllegalArgumentException("Unexpected state value " + state);
    }

    private static Event upEvent(State state) {
        switch (state) {
            case INITIALIZED:
            case DESTROYED:
                return ON_CREATE;
            case CREATED:
                return ON_START;
            case STARTED:
                return ON_RESUME;
            case RESUMED:
                throw new IllegalArgumentException();
        }
        throw new IllegalArgumentException("Unexpected state value " + state);
    }
}复制代码
public class LifecycleRegistry extends Lifecycle {

    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 static Event downEvent(State state) {
        switch (state) {
            case INITIALIZED:
                throw new IllegalArgumentException();
            case CREATED:
                return ON_DESTROY;
            case STARTED:
                return ON_STOP;
            case RESUMED:
                return ON_PAUSE;
            case DESTROYED:
                throw new IllegalArgumentException();
        }
        throw new IllegalArgumentException("Unexpected state value " + state);
    }

    private static Event upEvent(State state) {
        switch (state) {
            case INITIALIZED:
            case DESTROYED:
                return ON_CREATE;
            case CREATED:
                return ON_START;
            case STARTED:
                return ON_RESUME;
            case RESUMED:
                throw new IllegalArgumentException();
        }
        throw new IllegalArgumentException("Unexpected state value " + state);
    }
}复制代码

这三个方法,可以总结为下面这样一张图:

downEvent 在图中表示从一个状态到他下面的那个状态,upEvent 则是往上。

了解了 Lifecycle 的状态后,我们继续来看 LifecycleRegistry。上面我们知道,当Activity的生命周期发生变化后,ReportFragment会感知到,从而会调用到dispatch方法,最终调用到LifecycleRegistry的 handleLifecycleEvent方法:

public class LifecycleRegistry extends Lifecycle {

    private int mAddingObserverCounter = 0;

    private boolean mHandlingEvent = false;
    private boolean mNewEventOccurred = false;

    public void handleLifecycleEvent(@NonNull Lifecycle.Event event) {
        State next = getStateAfter(event);
        moveToState(next);
    }

    private void moveToState(State next) {
        if (mState == next) {
            return;
        }
        mState = next;
        // 当我们在 LifecycleRegistry 回调 LifecycleObserver 的时候触发状态变化时,
        // mHandlingEvent 为 true;
        // 添加 observer 的时候,也可能会执行回调方法,这时候如果触发了状态变化,
        // 则 mAddingObserverCounter != 0
        if (mHandlingEvent || mAddingObserverCounter != 0) {
            mNewEventOccurred = true;
            // 不需要执行 sync。
            // 执行到这里的情况是:sync() -> LifecycleObserver -> moveToState()
            // 这里直接返回后,还是会回到 sync(),然后继续同步状态给 observer
            // we will figure out what to do on upper level.
            return;
        }
        mHandlingEvent = true;
        // sync() 会把状态的变化转化为生命周期事件,然后转发给 LifecycleObserver
        sync();
        mHandlingEvent = false;
    }
}复制代码
public class LifecycleRegistry extends Lifecycle {

    private int mAddingObserverCounter = 0;

    private boolean mHandlingEvent = false;
    private boolean mNewEventOccurred = false;

    public void handleLifecycleEvent(@NonNull Lifecycle.Event event) {
        State next = getStateAfter(event);
        moveToState(next);
    }

    private void moveToState(State next) {
        if (mState == next) {
            return;
        }
        mState = next;
        // 当我们在 LifecycleRegistry 回调 LifecycleObserver 的时候触发状态变化时,
        // mHandlingEvent 为 true;
        // 添加 observer 的时候,也可能会执行回调方法,这时候如果触发了状态变化,
        // 则 mAddingObserverCounter != 0
        if (mHandlingEvent || mAddingObserverCounter != 0) {
            mNewEventOccurred = true;
            // 不需要执行 sync。
            // 执行到这里的情况是:sync() -> LifecycleObserver -> moveToState()
            // 这里直接返回后,还是会回到 sync(),然后继续同步状态给 observer
            // we will figure out what to do on upper level.
            return;
        }
        mHandlingEvent = true;
        // sync() 会把状态的变化转化为生命周期事件,然后转发给 LifecycleObserver
        sync();
        mHandlingEvent = false;
    }
}复制代码

LifecycleRegistry 本来要做的事其实是很简单的,但由于他需要执行客户的代码,由此引入了很多额外的复杂度。原因是,客户代码并不处在我们的控制之下,他们可能做出任何可以做到的事。例如这里,在回调中又触发状态变化。类似的情况是,在持有锁的时候不调用客户代码,这个也会让实现变得比较复杂。

接下来我们看 sync():

public class LifecycleRegistry extends Lifecycle {

    /**
     * Custom list that keeps observers and can handle removals / additions during traversal.
     *
     * 这个 Invariant 非常重要,他会影响到 sync() 的逻辑
     * Invariant: at any moment of time for observer1 & observer2:
     * if addition_order(observer1) < addition_order(observer2), then
     * state(observer1) >= state(observer2),
     */
    private FastSafeIterableMap<LifecycleObserver, ObserverWithState> mObserverMap =
            new FastSafeIterableMap<>();

    private void sync() {
        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 是为了在 observer 触发状态变化时让 backwardPass/forwardPass()
            // 提前返回用的。我们刚准备调他们,这里设置为 false 即可。
            mNewEventOccurred = false;
            // no need to check eldest for nullability, because isSynced does it for us.
            if (mState.compareTo(mObserverMap.eldest().getValue().mState) < 0) {
                // mObserverMap 里的元素的状态是非递增排列的,也就是说,队头的 state 最大
                // 如果 mState 小于队列里最大的那个,说明有元素需要更新状态
                // 为了维持 mObserverMap 的 Invariant,这里我们需要从队尾往前更新元素的状态
                backwardPass(lifecycleOwner);
            }
            Entry<LifecycleObserver, ObserverWithState> newest = mObserverMap.newest();
            // 如果 mNewEventOccurred,说明在上面调用 backwardPass() 时,客户触发了状态修改
            if (!mNewEventOccurred && newest != null
                    && mState.compareTo(newest.getValue().mState) > 0) {
                forwardPass(lifecycleOwner);
            }
        }
        mNewEventOccurred = false;
    }

    // 判断是否需要同步,如果所有的observer的状态都已经同步完,返回 true,否则返回false
    private boolean isSynced() {
        if (mObserverMap.size() == 0) {
            return true;
        }
        //eldestObserverState是最早添加的observer,newestObserverState是最新添加的observer
        State eldestObserverState = mObserverMap.eldest().getValue().mState;
        State newestObserverState = mObserverMap.newest().getValue().mState;
        //因为我们保证队头的state >= 后面的元素的state,所以只要判断头尾就够了
        //如果最新的和最老的Observer的状态不一致或者当前的状态和最新的状态不一致时,那么需要进行状态同步
        return eldestObserverState == newestObserverState && mState == newestObserverState;
    }

}复制代码
public class LifecycleRegistry extends Lifecycle {

    /**
     * Custom list that keeps observers and can handle removals / additions during traversal.
     *
     * 这个 Invariant 非常重要,他会影响到 sync() 的逻辑
     * Invariant: at any moment of time for observer1 & observer2:
     * if addition_order(observer1) < addition_order(observer2), then
     * state(observer1) >= state(observer2),
     */
    private FastSafeIterableMap<LifecycleObserver, ObserverWithState> mObserverMap =
            new FastSafeIterableMap<>();

    private void sync() {
        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 是为了在 observer 触发状态变化时让 backwardPass/forwardPass()
            // 提前返回用的。我们刚准备调他们,这里设置为 false 即可。
            mNewEventOccurred = false;
            // no need to check eldest for nullability, because isSynced does it for us.
            if (mState.compareTo(mObserverMap.eldest().getValue().mState) < 0) {
                // mObserverMap 里的元素的状态是非递增排列的,也就是说,队头的 state 最大
                // 如果 mState 小于队列里最大的那个,说明有元素需要更新状态
                // 为了维持 mObserverMap 的 Invariant,这里我们需要从队尾往前更新元素的状态
                backwardPass(lifecycleOwner);
            }
            Entry<LifecycleObserver, ObserverWithState> newest = mObserverMap.newest();
            // 如果 mNewEventOccurred,说明在上面调用 backwardPass() 时,客户触发了状态修改
            if (!mNewEventOccurred && newest != null
                    && mState.compareTo(newest.getValue().mState) > 0) {
                forwardPass(lifecycleOwner);
            }
        }
        mNewEventOccurred = false;
    }

    // 判断是否需要同步,如果所有的observer的状态都已经同步完,返回 true,否则返回false
    private boolean isSynced() {
        if (mObserverMap.size() == 0) {
            return true;
        }
        //eldestObserverState是最早添加的observer,newestObserverState是最新添加的observer
        State eldestObserverState = mObserverMap.eldest().getValue().mState;
        State newestObserverState = mObserverMap.newest().getValue().mState;
        //因为我们保证队头的state >= 后面的元素的state,所以只要判断头尾就够了
        //如果最新的和最老的Observer的状态不一致或者当前的状态和最新的状态不一致时,那么需要进行状态同步
        return eldestObserverState == newestObserverState && mState == newestObserverState;
    }

}复制代码

sync() 的主要作用就是根据把 mObserverMap 里所有元素的状态都同步为 mState。我们继续看剩下的 backwardPass/forwardPass:

public class LifecycleRegistry extends Lifecycle {

    // 这段注释应该是这整个类里面最难理解的了吧,至少对于我来说是这样
    // we have to keep it for cases:
    // void onStart() {
    //     // removeObserver(this),说明 this 是一个 LifecycleObserver
    //     // 所以这里说的是,我们在回调里执行了下面两个操作
    //     mRegistry.removeObserver(this);
    //     mRegistry.add(newObserver);
    // }
    // 假定现在我们要从 CREATED 转到 STARTED 状态(也就是说,mState 现在是 STARTED)。
    // 这种情况下,只有将新的 observer 设置为 CREATED 状态,它的 onStart 才会被调用
    // 为了得到这个 CREATED,在这里才引入了 mParentStates。在 forwardPass 中执行
    // pushParentState(observer.mState) 时,observer.mState 就是我们需要的 CREATED。
    // backwardPass 的情况类似。
    // newObserver should be brought only to CREATED state during the execution of
    // this onStart method. our invariant with mObserverMap doesn't help, because parent observer
    // is no longer in the map.
    private ArrayList<State> mParentStates = new ArrayList<>();

    //第一个while循坏遍历我们存储观察者的集合,
    //第二个是要处理各个状态经过的event
    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);
                //upEvent 返回所要经历的event
                //例如:当前是 STARTED , 那么他的经过的 events 就是 ON_RESUME
                observer.dispatchEvent(lifecycleOwner, upEvent(observer.mState));
                popParentState();
            }
        }
    }

    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 popParentState() {
        mParentStates.remove(mParentStates.size() - 1);
    }

    private void pushParentState(State state) {
        mParentStates.add(state);
    }
}复制代码
public class LifecycleRegistry extends Lifecycle {

    // 这段注释应该是这整个类里面最难理解的了吧,至少对于我来说是这样
    // we have to keep it for cases:
    // void onStart() {
    //     // removeObserver(this),说明 this 是一个 LifecycleObserver
    //     // 所以这里说的是,我们在回调里执行了下面两个操作
    //     mRegistry.removeObserver(this);
    //     mRegistry.add(newObserver);
    // }
    // 假定现在我们要从 CREATED 转到 STARTED 状态(也就是说,mState 现在是 STARTED)。
    // 这种情况下,只有将新的 observer 设置为 CREATED 状态,它的 onStart 才会被调用
    // 为了得到这个 CREATED,在这里才引入了 mParentStates。在 forwardPass 中执行
    // pushParentState(observer.mState) 时,observer.mState 就是我们需要的 CREATED。
    // backwardPass 的情况类似。
    // newObserver should be brought only to CREATED state during the execution of
    // this onStart method. our invariant with mObserverMap doesn't help, because parent observer
    // is no longer in the map.
    private ArrayList<State> mParentStates = new ArrayList<>();

    //第一个while循坏遍历我们存储观察者的集合,
    //第二个是要处理各个状态经过的event
    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);
                //upEvent 返回所要经历的event
                //例如:当前是 STARTED , 那么他的经过的 events 就是 ON_RESUME
                observer.dispatchEvent(lifecycleOwner, upEvent(observer.mState));
                popParentState();
            }
        }
    }

    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 popParentState() {
        mParentStates.remove(mParentStates.size() - 1);
    }

    private void pushParentState(State state) {
        mParentStates.add(state);
    }
}复制代码

提示:在看这forwardPass以及backwardPass这两个方法时,参考上面的状态转换图

  1. 假设当前集合中所有ObserverWithState元素都处于CREATED状态。此时接着收到了一个ON_START事件,从图可以看出,接下来应该是要转换到STARTED状态。由于STARTED大于CREATED,所以会执行forwardPass方法。forwardPass里调用 upEvent(observer.mState),返回从CREATED往上到STARTED需要发送的事件,也就是ON_START,于是ON_START事件发送给了观察者。
  2. 假设当前 LifecycleRegistrymState处于RESUMED状态。然后调用addObserver方法新添加一个LifecycleObserver,该observer会被封装成ObserverWithState存进集合中,此时这个新的ObserverWithState处于INITIALIZED状态,由于RESUMED大于INITIALIZED,所以会执行forwardPass方法。ObserverWithState状态会按照 INITIALIZED -> CREATED -> STARTED -> RESUMED 这样的顺序变迁。


总结

一些个人疑问:

  • 疑点1:为什么不直接在SupportActivity的生命周期函数中给Lifecycle分发生命周期事件,而是要加一个Fragment呢?

因为不是所有的页面都继承AppCompatActivity,为了兼容非AppCompatActivity,所以封装一个同样具有生命周期的Fragment来给Lifecycle分发生命周期事件。显然Fragment 侵入性低。

  • 疑点2:为什么用ReportFragment分发生命周期而不直接使用ActivityLifecycleCallbacks的回调来处理Lifecycle生命周期的变化?

由于 ActivityLifecycleCallbacks 的回调比 Fragment 和 Activity 还要早,实际上未真正执行对应的生命周期方法


Lifecycle的分析我们在这里就到此为止了,最后附上幅流程图,帮助理解并记忆: