Lifecycle全面剖析

一、简介

Lifecycle 库是2017年 Google I/O 开发者大会上发布的一个库,目的是让除了 Activity 和 Fragment 外的其他组件也能感知到生命周期。

那为什么要用Lifecycle呢?

举一下我们最常用的 MVP 例子,没引进 Lifecycle 之前,我们需要在 Activity 或者 Fragment 销毁的时候,即 onDestroy 的时候手动调用 Presenter的onDestroy 方法,这里会带来一些问题,每一次在 Activity 或者 Fragment 销毁的时候都要调用 presenter.destory() 方法,如果有多个Presenter,则需要调用多遍,想要传递其他生命周期也是类似,需要调用多遍,这样的代码一点也不优雅

而引入lifecycle之后,我们就可以在presenter中自己手动监听Activity或者Fragment生命周期,自己处理自己的销毁或释放逻辑,而上层Activity或者Fragment无需关心,一定程度上解耦了代码 & 避免了内存泄漏。

具体使用方式我们在了解他的各个库中的类及具体作用之后再细讲。

二、各个库的了解

目前我们已经升级了AndroidX,我们先来简单看一下AndroidX下面的依赖关系

所以其实我们只要依赖了AndroidX的appcompat库,就自动帮我们依赖了lifecycle的runtime库和common库, 其中runtime库是依赖common库的

Lifecycle相关的库有很多,我们大概看一下:

dependencies {
        def lifecycle_version = "2.2.0"
        def arch_version = "2.1.0"
 
        // ViewModel
        implementation "androidx.lifecycle:lifecycle-viewmodel:$lifecycle_version"
        // LiveData
        implementation "androidx.lifecycle:lifecycle-livedata:$lifecycle_version"
        // Lifecycles only (without ViewModel or LiveData)
        implementation "androidx.lifecycle:lifecycle-runtime:$lifecycle_version"
 
        // Saved state module for ViewModel
        implementation "androidx.lifecycle:lifecycle-viewmodel-savedstate:$lifecycle_version"
 
        // Annotation processor
        annotationProcessor "androidx.lifecycle:lifecycle-compiler:$lifecycle_version"
        // alternately - if using Java8, use the following instead of lifecycle-compiler
        implementation "androidx.lifecycle:lifecycle-common-java8:$lifecycle_version"
 
        // optional - helpers for implementing LifecycleOwner in a Service
        implementation "androidx.lifecycle:lifecycle-service:$lifecycle_version"
 
        // optional - ProcessLifecycleOwner provides a lifecycle for the whole application process
        implementation "androidx.lifecycle:lifecycle-process:$lifecycle_version"
 
        // optional - ReactiveStreams support for LiveData
        implementation "androidx.lifecycle:lifecycle-reactivestreams:$lifecycle_version"
 
        // optional - Test helpers for LiveData
        testImplementation "androidx.arch.core:core-testing:$arch_version"
}

下面我们重点分析一下一些常用的库

lifecycle-common

这个库是Lifecycle的基础库,主要包含基础类或接口的定义,相当于Lifecycle底层服务库
Lifecycle全面剖析_第1张图片

下面看我们经常使用到的类:

LifecycleOwner: 是一个接口,接口通常用来声明具备某种能力。该接口的能力就是具有生命周期。 AndroidX 中 AppCompatActivity、Fragment都已经直接或间接的实现了该接口。 内部定义了getLifecycle()方法

public interface LifecycleOwner {
    /**
     * Returns the Lifecycle of the provider.
     *
     * @return The lifecycle of the provider.
     */
    @NonNull
    Lifecycle getLifecycle();
}

Lifecycle: 抽象类, 添加观察者、删除观察者等方法, 内部定义了 Event 和 State 枚举类

public abstract class Lifecycle {
 
    /**
     * Lifecycle coroutines extensions stashes the CoroutineScope into this field.
     *
     * @hide used by lifecycle-common-ktx
     */
    @RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)
    @NonNull
    AtomicReference<Object> mInternalScopeRef = new AtomicReference<>();
 
    /**
     * Adds a LifecycleObserver that will be notified when the LifecycleOwner changes
     * state.
     * 

* The given observer will be brought to the current state of the LifecycleOwner. * For example, if the LifecycleOwner is in {@link State#STARTED} state, the given observer * will receive {@link Event#ON_CREATE}, {@link Event#ON_START} events. * * @param observer The observer to notify. */ @MainThread public abstract void addObserver(@NonNull LifecycleObserver observer); /** * Removes the given observer from the observers list. *

* If this method is called while a state change is being dispatched, *

    *
  • If the given observer has not yet received that event, it will not receive it. *
  • If the given observer has more than 1 method that observes the currently dispatched * event and at least one of them received the event, all of them will receive the event and * the removal will happen afterwards. *
* * @param observer The observer to be removed. */
@MainThread public abstract void removeObserver(@NonNull LifecycleObserver observer); /** * Returns the current state of the Lifecycle. * * @return The current state of the Lifecycle. */ @MainThread @NonNull public abstract State getCurrentState(); @SuppressWarnings("WeakerAccess") 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 } /** * Lifecycle states. You can consider the states as the nodes in a graph and * {@link Event}s as the edges between these nodes. */ @SuppressWarnings("WeakerAccess") 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 * right before 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: *
    *
  • after {@link android.app.Activity#onCreate(android.os.Bundle) onCreate} call; *
  • right before {@link android.app.Activity#onStop() onStop} call. *
*/
CREATED, /** * Started state for a LifecycleOwner. For an {@link android.app.Activity}, this state * is reached in two cases: *
    *
  • after {@link android.app.Activity#onStart() onStart} call; *
  • right before {@link android.app.Activity#onPause() onPause} call. *
*/
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; /** * Compares if this State is greater or equal to the given {@code state}. * * @param state State to compare with * @return true if this State is greater or equal to the given {@code state} */ public boolean isAtLeast(@NonNull State state) { return compareTo(state) >= 0; } } }

LifecycleObserver: 一个空接口,定义生命周期观察者。
OnLifecycleEvent: 用来注解要观察的生命周期事件

所以

LifecycleOwner是生命周期持有者

LifecycleObserver是生命周期观察者

Lifecycle就是他们之间联系的桥梁, 可以添加和删除观察者,另外还需要给观察者分发生命周期事件,但是Lifecycle是抽象类,只是定义了某些方法、事件、状态,所以需要有具体的实现去做这些事情。

lifecycle-runtime

这个库中的类就是我们上面说的需要真正做事情的类所在的库, 相当于Lifecycle上层封装库,供开发者直接使用
Lifecycle全面剖析_第2张图片
LifeclecycleRegistry : 继承自Lifecycle ,并重写相关抽象方法,补全了生命周期分发逻辑,后面源码分析的时候我们详细分析该类的实现
ReportFragment: 真正分发生命周期的入口,调用LifecycleRegistry相关方法, 后面源码分析进行说明

整体来看 对应类图为:
Lifecycle全面剖析_第3张图片

lifecycle-compiler

编译期间生成代码的库

Lifecycle 可以选择使用 apt 编译期生成代码来避免使用运行时反射,以优化性能
如果你的观察者监听生命周期直接实现了LifecycleObserver接口,并且通过@OnLifecycleEvent 注解监听生命周期,那么使用该库就会在编译期间生成相关代码

先大概对比一下源代码和生成的代码:
Lifecycle全面剖析_第4张图片
Lifecycle全面剖析_第5张图片

可以看到使用apt在编译期间生成辅助类,最终是直接进行方法调用的,而不是反射

当然如果你不通过 annotationProcessor 依赖该库的话,是不会在编译期间生成代码的,那么最终还是通过反射来操作

lifecycle-process

Lifecycle全面剖析_第6张图片
该库是用来监听Application生命周期的,一般用来判断应用是在前台还是后台。

也是基于Lifecycle分发生命周期,然后加上一些逻辑控制,保证整个应用期间切前后台的时候ON_CREATE 只会回调一次,ON_START,ON_RESUME 在切前台时调用,ON_PAUSE, ON_STOP 在切后台的时候调用,让你很方便判断出应用的前后台状态。

lifecycle-service

将Service也为我们实现了LifecycleOwner, 并且分发了相关生命周期,如果有需要可以直接继承LifecycleService来使其他类能感知到Service的生命周期
Lifecycle全面剖析_第7张图片

三、 Lifecycle的使用

监听Activity或者Fragment生命周期

由于我们目前开发一般都会继承AppCompatActivity 或者Fragment去开发界面,而Google也已经帮我们处理好了其生命周期的分发,所以我们如果想监听Activity或者Fragment生命周期,可以直接通过getLifecycle.addObserver()来实现

而LifecycleObserver有多种实现方式:

1. 直接实现LifecycleObserver, 然后监听对应生命周期方法通过注解来实现

public class MainActivity extends AppCompatActivity implements View.OnClickListener {
    private String TAG = MainActivity.class.getSimpleName();
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
 
        //直接使用匿名内部类的观察者  实现LifecycleObserver接口
        getLifecycle().addObserver(new LifecycleObserver() {
            @OnLifecycleEvent(Lifecycle.Event.ON_CREATE)
            public void onCreate() {
                Log.d(TAG, "OnLifecycleEvent onCreate");
            }
 
            @OnLifecycleEvent(Lifecycle.Event.ON_RESUME)
            public void onResume() {
                Log.d(TAG, "OnLifecycleEvent onResume");
            }
        });
 
        //使用外部实现LifecycleObserver接口的类
        getLifecycle().addObserver(new MySimpleLifecycleObserver());
    }
}
 
 
public class MySimpleLifecycleObserver implements LifecycleObserver {
    private String TAG = MySimpleLifecycleObserver.class.getSimpleName();
 
    @OnLifecycleEvent(Lifecycle.Event.ON_CREATE)
    public void onCreate() {
        Log.d(TAG, "onCreate");
    }
 
    @OnLifecycleEvent(Lifecycle.Event.ON_RESUME)
    public void onResume() {
        Log.d(TAG, "onResume");
    }
 
 
    @OnLifecycleEvent(Lifecycle.Event.ON_PAUSE)
    public void onPause() {
        Log.d(TAG, "onPause");
    }
 
 
    @OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
    public void onDestroy() {
        Log.d(TAG, "onDestroy");
    }
}

需要注意的是:上面我们一种通过匿名内部类实现LifecycleObserver接口,一种是外部类实现LifecycleObserver接口,这两种方式看起来没什么区别,但是在执行过程中其实是有区别的,在使用apt的情况下,匿名内部类的最终使用反射分发生命周期,而外部类这种使用生成的代码直接调用

2. 使用LifecycleEventObserver

public class MainActivity extends AppCompatActivity {
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
     
        //使用实现LifecycleEventObserver接口的类
        getLifecycle().addObserver(new MyLifecycleEventObserver());
    }
}
 
 
 
public class MyLifecycleEventObserver implements LifecycleEventObserver {
    private String TAG = MyLifecycleEventObserver.class.getSimpleName();
 
    //这里能拿到所有生命周期事件
    @Override
    public void onStateChanged(@NonNull LifecycleOwner source, @NonNull Lifecycle.Event event) {
        Log.d(TAG, "onStateChanged " + event);
    }
 
    //注意 不会执行
    @OnLifecycleEvent(Lifecycle.Event.ON_CREATE)
    public void onCreate() {
        Log.d(TAG, "onCreate");
    }
 
    //注意 不会执行
    @OnLifecycleEvent(Lifecycle.Event.ON_RESUME)
    public void onResume() {
        Log.d(TAG, "onResume");
    }
 
 
    //注意 不会执行
    @OnLifecycleEvent(Lifecycle.Event.ON_PAUSE)
    public void onPause() {
        Log.d(TAG, "onPause");
    }
 
    //注意 不会执行
    @OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
    public void onDestroy() {
        Log.d(TAG, "onDestroy");
    }
}

需要注意的是,如果使用 LifecycleEventObserver, 则相应注解@OnLifecycleEvent 监听的生命周期的方法将不会被调用,而是统一通过onStateChanged分发,所以这种情况就不要再使用注解了。

3. 使用DefaultLifecycleObserver

DefaultLifecycleObserver是 lifecycle-common-java8库中的一个类,至于为什么叫java8, 是因为该类实现了FullLifecycleObserver接口,重写了onCreate onResume等生命周期方法,并且方法前面加了default修饰符

而default修饰符在java8上面表示接口可以有默认方法了,当你实现该接口的时候,default的修饰符的方法不是强制必须重写的

所以如果你的编译的java环境如果是java8 可以直接使用该接口,并重写你想监听的生命周期方法

public class MyDefaultLifecycleObserver implements DefaultLifecycleObserver {
 
    private String TAG = MyDefaultLifecycleObserver.class.getSimpleName();
 
 
    @Override
    public void onCreate(@NonNull LifecycleOwner owner) {
        Log.d(TAG, "onCreate");
    }
 
 
    @Override
    public void onResume(@NonNull LifecycleOwner owner) {
        Log.d(TAG, "onResume");
    }
}
 
 
getLifecycle().addObserver(new MyDefaultLifecycleObserver());

需要注意的是,虽然这个库是lifecycle-common-java8, 但是假如你的java环境是小于1.8,仍然可以使用该库,也可以使用DefaultLifecycleObserver

区别在于1.8之下default关键字不生效,所以使用该接口要把所有的生命周期方法都实现,不然会编译不通过

另外其实Google是比较推荐使用这种方式去监听生命周期的,因为这种在源码中是最简单的执行流程, 后面我们分析源码的时候也能看出来。

我们先看下该类的实现

/**
 * Callback interface for listening to {@link LifecycleOwner} state changes.
 * 

* If you use Java 8 language, always prefer it over annotations. *

* If a class implements both this interface and {@link LifecycleEventObserver}, then * methods of {@code DefaultLifecycleObserver} will be called first, and then followed by the call * of {@link LifecycleEventObserver#onStateChanged(LifecycleOwner, Lifecycle.Event)} *

* If a class implements this interface and in the same time uses {@link OnLifecycleEvent}, then * annotations will be ignored. */ @SuppressWarnings("unused") public interface DefaultLifecycleObserver extends FullLifecycleObserver { /** * Notifies that {@code ON_CREATE} event occurred. *

* This method will be called after the {@link LifecycleOwner}'s {@code onCreate} * method returns. * * @param owner the component, whose state was changed */ @Override default void onCreate(@NonNull LifecycleOwner owner) { } /** * Notifies that {@code ON_START} event occurred. *

* This method will be called after the {@link LifecycleOwner}'s {@code onStart} method returns. * * @param owner the component, whose state was changed */ @Override default void onStart(@NonNull LifecycleOwner owner) { } /** * Notifies that {@code ON_RESUME} event occurred. *

* This method will be called after the {@link LifecycleOwner}'s {@code onResume} * method returns. * * @param owner the component, whose state was changed */ @Override default void onResume(@NonNull LifecycleOwner owner) { } /** * Notifies that {@code ON_PAUSE} event occurred. *

* This method will be called before the {@link LifecycleOwner}'s {@code onPause} method * is called. * * @param owner the component, whose state was changed */ @Override default void onPause(@NonNull LifecycleOwner owner) { } /** * Notifies that {@code ON_STOP} event occurred. *

* This method will be called before the {@link LifecycleOwner}'s {@code onStop} method * is called. * * @param owner the component, whose state was changed */ @Override default void onStop(@NonNull LifecycleOwner owner) { } /** * Notifies that {@code ON_DESTROY} event occurred. *

* This method will be called before the {@link LifecycleOwner}'s {@code onDestroy} method * is called. * * @param owner the component, whose state was changed */ @Override default void onDestroy(@NonNull LifecycleOwner owner) { } }

监听其他拥有生命周期类的生命周期

上面我们说的是AppCompatActivity 和Fragment的生命周期的监听,那假如我有一个类,该类也具有生命周期,其他类也需要感知我这个类的生命周期,那怎么做呢?

这个时候我们就需要自己实现LifecycleOwner接口,创建Lifecycle对象,分发该类的生命周期,具体代码简单实现为

public class MyLifecycleOwner implements LifecycleOwner {
    private String TAG = MyLifecycleOwner.class.getSimpleName();
    private LifecycleRegistry lifecycleRegistry;
 
    public void onCreate() {
        lifecycleRegistry = new LifecycleRegistry(this);
 
        getLifecycle().addObserver(new DefaultLifecycleObserver() {
            @Override
            public void onCreate(@NonNull LifecycleOwner owner) {
                Log.d(TAG, "MyLifecycleOwner onCreate");
            }
 
            @Override
            public void onDestroy(@NonNull LifecycleOwner owner) {
                Log.d(TAG, "MyLifecycleOwner onDestroy");
            }
        });
 
        //在合适的机会分发生命周期
        lifecycleRegistry.handleLifecycleEvent(Lifecycle.Event.ON_CREATE);
    }
 
    public void onDestroy() {
        //在合适的机会分发生命周期
        lifecycleRegistry.handleLifecycleEvent(Lifecycle.Event.ON_DESTROY);
    }
 
    @NonNull
    @Override
    public Lifecycle getLifecycle() {
        return lifecycleRegistry;
    }
}

其实对于在Android中,对于任意一个类来说,他的生命周期基本上也是Activity或者Fragment赋予的,所以你可以将Activity或者Fragment的Lifecycle对象传递进来,监听的时候直接使用相应传递进来的Lifecycle对象,但是如果你不想那样做或者由于老代码不好改动那么就可以像上面那样做,自己去创建LifecycleRegistry对象,自己在合适的时机去分发相应生命周期。

Lifecycle应用场景

比如注册事件,正常来说我们为了减少内存泄漏,在某个类比如Activity中需要出现成对的注册和反注册方法,但是有了Lifecycle,我们就可以将反注册进行自动的实现了

  1. 比如注册的时候给工具类塞Lifecycle进去,那么工具类就可以自己监听生命周期的销毁然后进行相应的反注册了。

  2. 在Kotlin协程中,也可以给协程作用域塞入Lifecycle, 然后在onDestroy的时候取消掉当前作用域内的所有Job

//创建主线程协程作用域
LifecycleCoroutineScope mainCoroutineScope = new LifecycleCoroutineScope(this, Dispatchers.getMain());
 
 
//执行协程操作
fun <T : IView> IPresenter<T>.launch(block: suspend CoroutineScope.() -> Unit): Job? {
    return this.mainCoroutineScope.launch { block.invoke(this) }
}
 
 
class LifecycleCoroutineScope(lifecycleOwner: LifecycleOwner, dispatcher: CoroutineDispatcher) :
    CoroutineScope, LifecycleObserver {
    override val coroutineContext: CoroutineContext = SupervisorJob() + dispatcher
 
    init {
        lifecycleOwner.lifecycle.addObserver(this)
    }
 
    //监听ON_DESTROY生命周期,取消所有job
    @OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
    fun onDestroy() {
        coroutineContext.cancel()
    }
}

监听App 生命周期

ProcessLifecycleOwner.get().getLifecycle().addObserver(new MyAppLifecycleListener());

observer的创建方式跟上面监听Activity Fragment生命周期中的observer创建方式类似

执行的结果会是:onCreate在应用执行期间只会调用一次,其他方法onStart onResume onPause onStop在切前后台的时候可能会被调用多次,但是注意onDestroy不会被回调

四、源码分析

我们上面提到过一个类叫ReportFragment,针对Activity生命周期事件的分发就是在该类中进行

将ReportFragment添加到ComponentActivity中,然后在fragment生命周期方法中进行分发:

//ComponentActivity
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    ...
    //注入ReportFragment
    ReportFragment.injectIfNeededIn(this);
    ...
}
 
//ReportFragment
public class ReportFragment extends Fragment {
    private static final String REPORT_FRAGMENT_TAG = "androidx.lifecycle"
            + ".LifecycleDispatcher.report_fragment_tag";
 
    public static void injectIfNeededIn(Activity activity) {
        if (Build.VERSION.SDK_INT >= 29) {
            // On API 29+, we can register for the correct Lifecycle callbacks directly
            activity.registerActivityLifecycleCallbacks(
                    new LifecycleCallbacks());
        }
        // Prior to API 29 and to maintain compatibility with older versions of
        // ProcessLifecycleOwner (which may not be updated when lifecycle-runtime is updated and
        // need to support activities that don't extend from FragmentActivity from support lib),
        // use a framework fragment to get the correct timing of Lifecycle events
        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();
        }
    }
 
    @SuppressWarnings("deprecation")
    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);
            }
        }
    }
 
    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(@NonNull Lifecycle.Event event) {
        if (Build.VERSION.SDK_INT < 29) {
            // Only dispatch events from ReportFragment on API levels prior
            // to API 29. On API 29+, this is handled by the ActivityLifecycleCallbacks
            // added in ReportFragment.injectIfNeededIn
            dispatch(getActivity(), event);
        }
    }
 
    void setProcessListener(ActivityInitializationListener processListener) {
        mProcessListener = processListener;
    }
 
    interface ActivityInitializationListener {
        void onCreate();
 
        void onStart();
 
        void onResume();
    }
 
    // this class isn't inlined only because we need to add a proguard rule for it. (b/142778206)
    static class LifecycleCallbacks implements Application.ActivityLifecycleCallbacks {
        @Override
        public void onActivityCreated(@NonNull Activity activity,
                @Nullable Bundle bundle) {
        }
 
        @Override
        public void onActivityPostCreated(@NonNull Activity activity,
                @Nullable Bundle savedInstanceState) {
            dispatch(activity, Lifecycle.Event.ON_CREATE);
        }
 
        @Override
        public void onActivityStarted(@NonNull Activity activity) {
        }
 
        @Override
        public void onActivityPostStarted(@NonNull Activity activity) {
            dispatch(activity, Lifecycle.Event.ON_START);
        }
 
        @Override
        public void onActivityResumed(@NonNull Activity activity) {
        }
 
        @Override
        public void onActivityPostResumed(@NonNull Activity activity) {
            dispatch(activity, Lifecycle.Event.ON_RESUME);
        }
 
        @Override
        public void onActivityPrePaused(@NonNull Activity activity) {
            dispatch(activity, Lifecycle.Event.ON_PAUSE);
        }
 
        @Override
        public void onActivityPaused(@NonNull Activity activity) {
        }
 
        @Override
        public void onActivityPreStopped(@NonNull Activity activity) {
            dispatch(activity, Lifecycle.Event.ON_STOP);
        }
 
        @Override
        public void onActivityStopped(@NonNull Activity activity) {
        }
 
        @Override
        public void onActivitySaveInstanceState(@NonNull Activity activity,
                @NonNull Bundle bundle) {
        }
 
        @Override
        public void onActivityPreDestroyed(@NonNull Activity activity) {
            dispatch(activity, Lifecycle.Event.ON_DESTROY);
        }
 
        @Override
        public void onActivityDestroyed(@NonNull Activity activity) {
        }
    }
}

可以看到最终是通过调用 LifecycleRegistry.handleLifecycleEvent 进行生命周期的分发

但是你可能会发现里面还有一个 mProcessListener, 这个listener是做什么用的呢?什么时候设置的呢?

其实这个就是为监听整个应用生命周期服务的,接下来我们进行分析:

在lifecycle-process这个库中,有一个叫 ProcessLifecycleOwnerInitializer,该类继承自 ContentProvider, 用于做一些初始化操作

public class ProcessLifecycleOwnerInitializer extends ContentProvider {
    @Override
    public boolean onCreate() {
        LifecycleDispatcher.init(getContext());
        ProcessLifecycleOwner.init(getContext());
        return true;
    }
 
    ... //其他方法没做什么操作,此处省略
}
 
 
class LifecycleDispatcher {
 
    private static AtomicBoolean sInitialized = new AtomicBoolean(false);
 
    static void init(Context context) {
        if (sInitialized.getAndSet(true)) {
            return;
        }
        ((Application) context.getApplicationContext())
                .registerActivityLifecycleCallbacks(new DispatcherActivityCallback());
    }
 
    @SuppressWarnings("WeakerAccess")
    @VisibleForTesting
    static class DispatcherActivityCallback extends EmptyActivityLifecycleCallbacks {
 
        @Override
        public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
            //activity创建的时候注入ReportFragment
            ReportFragment.injectIfNeededIn(activity);
        }
 
        ...
    }
 
    private LifecycleDispatcher() {
    }
}
 
 
//实现LifecycleOwner接口,具备生命周期
public class ProcessLifecycleOwner implements LifecycleOwner {
 
    @VisibleForTesting
    static final long TIMEOUT_MS = 700; //mls
 
    // ground truth counters
    private int mStartedCounter = 0;
    private int mResumedCounter = 0;
 
    private boolean mPauseSent = true;
    private boolean mStopSent = true;
 
    private Handler mHandler;
    private final LifecycleRegistry mRegistry = new LifecycleRegistry(this);
 
    private Runnable mDelayedPauseRunnable = new Runnable() {
        @Override
        public void run() {
            //延时700ms才会去真正的分发ON_PAUSE ON_STOP生命周期
            dispatchPauseIfNeeded();
            dispatchStopIfNeeded();
        }
    };
 
    ActivityInitializationListener mInitializationListener =
            new ActivityInitializationListener() {
                @Override
                public void onCreate() {
                }
 
                @Override
                public void onStart() {
                    activityStarted();
                }
 
                @Override
                public void onResume() {
                    activityResumed();
                }
            };
 
    private static final ProcessLifecycleOwner sInstance = new ProcessLifecycleOwner();
 
    /**
     * The LifecycleOwner for the whole application process. Note that if your application
     * has multiple processes, this provider does not know about other processes.
     *
     * @return {@link LifecycleOwner} for the whole application.
     */
    @NonNull
    public static LifecycleOwner get() {
        return sInstance;
    }
 
    static void init(Context context) {
        sInstance.attach(context);
    }
 
    //分发ON_START生命周期
    void activityStarted() {
        mStartedCounter++;
        if (mStartedCounter == 1 && mStopSent) {
            mRegistry.handleLifecycleEvent(Lifecycle.Event.ON_START);
            mStopSent = false;
        }
    }
 
    //分发ON_RESUME生命周期
    void activityResumed() {
        mResumedCounter++;
        if (mResumedCounter == 1) {
            if (mPauseSent) {
                mRegistry.handleLifecycleEvent(Lifecycle.Event.ON_RESUME);
                mPauseSent = false;
            } else {
                //onPause之后立即又执行了onResume,则需要移除延时消息
                mHandler.removeCallbacks(mDelayedPauseRunnable);
            }
        }
    }
 
    void activityPaused() {
        mResumedCounter--;
        if (mResumedCounter == 0) {
            //做延时是为了避免比如屏幕旋转这样的操作,其实整个应用并没有切后台,所以不能立即分发ON_PAUSE生命周期
            mHandler.postDelayed(mDelayedPauseRunnable, TIMEOUT_MS);
        }
    }
 
    void activityStopped() {
        mStartedCounter--;
        dispatchStopIfNeeded();
    }
 
    //分发ON_PAUSE生命周期
    void dispatchPauseIfNeeded() {
        if (mResumedCounter == 0) {
            mPauseSent = true;
            mRegistry.handleLifecycleEvent(Lifecycle.Event.ON_PAUSE);
        }
    }
 
    //分发ON_STOP生命周期
    void dispatchStopIfNeeded() {
        //保证在pause之后分发
        if (mStartedCounter == 0 && mPauseSent) {
            mRegistry.handleLifecycleEvent(Lifecycle.Event.ON_STOP);
            mStopSent = true;
        }
    }
 
    private ProcessLifecycleOwner() {
    }
 
    void attach(Context context) {
        mHandler = new Handler();
        //这里直接分发ON_CREATE生命周期,因为应用创建了
        mRegistry.handleLifecycleEvent(Lifecycle.Event.ON_CREATE);
        Application app = (Application) context.getApplicationContext();
        app.registerActivityLifecycleCallbacks(new EmptyActivityLifecycleCallbacks() {
            @Override
            public void onActivityPreCreated(@NonNull Activity activity,
                    @Nullable Bundle savedInstanceState) {
                // We need the ProcessLifecycleOwner to get ON_START and ON_RESUME precisely
                // before the first activity gets its LifecycleOwner started/resumed.
                // The activity's LifecycleOwner gets started/resumed via an activity registered
                // callback added in onCreate(). By adding our own activity registered callback in
                // onActivityPreCreated(), we get our callbacks first while still having the
                // right relative order compared to the Activity's onStart()/onResume() callbacks.
 
 
                //在api 29的手机上直接可以通过该回调拿到界面被创建的回调, 并且时机比较靠后,能保证都在Activity onStart之后执行
                activity.registerActivityLifecycleCallbacks(new EmptyActivityLifecycleCallbacks() {
                    @Override
                    public void onActivityPostStarted(@NonNull Activity activity) {
                        activityStarted();
                    }
 
                    @Override
                    public void onActivityPostResumed(@NonNull Activity activity) {
                        activityResumed();
                    }
                });
            }
 
            @Override
            public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
                // Only use ReportFragment pre API 29 - after that, we can use the
                // onActivityPostStarted and onActivityPostResumed callbacks registered in
                // onActivityPreCreated()
                //lifecycle-process 2.2.0版本才有的该限制,之前的版本都统一设置ProcessListener
                if (Build.VERSION.SDK_INT < 29) {
                    //给ReportFragment设置ProcessListener来监听相应生命周期回调
                    //为什么要通过ReportFragment拿回调? 为什么不直接使用onActivityStarted onActivityStarted回调?
                    //是因为onActivityStarted  onActivityStarted回调会比Fragment里面onStart onResume回调早,为了使该事件分发尽量靠后,所以放在Fragment中,在ReportFragment内部分发给该listener
                    ReportFragment.get(activity).setProcessListener(mInitializationListener);
                }
            }
 
            @Override
            public void onActivityPaused(Activity activity) {
                activityPaused();
            }
 
            @Override
            public void onActivityStopped(Activity activity) {
                activityStopped();
            }
        });
    }
 
    @NonNull
    @Override
    public Lifecycle getLifecycle() {
        return mRegistry;
    }
}

上面所说的都是在合适的时机去调用LifecycleRegistry的handleLifecycleEvent方法分发生命周期,然后通过addObserver方法就能进行生命周期的监听了

那具体执行流程是什么呢?接下来我们就分析内部的具体执行逻辑:

在分析之前,我们先来看一下生命周期和对应状态的流转图:(对后面理解很重要)
Lifecycle全面剖析_第8张图片

public class LifecycleRegistry extends Lifecycle {
 
    /**
     * Custom list that keeps observers and can handle removals / additions during traversal.
     *
     * 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<>();
    /**
     * Current state
     */
    private State mState;
    /**
     * The provider that owns this Lifecycle.
     * Only WeakReference on LifecycleOwner is kept, so if somebody leaks Lifecycle, they won't leak
     * the whole Fragment / Activity. However, to leak Lifecycle object isn't great idea neither,
     * because it keeps strong references on all other listeners, so you'll leak all of them as
     * well.
     */
    private final WeakReference<LifecycleOwner> mLifecycleOwner;
 
    private int mAddingObserverCounter = 0;
 
    private boolean mHandlingEvent = false;
    private boolean mNewEventOccurred = false;
 
    // we have to keep it for cases:
    // void onStart() {
    //     mRegistry.removeObserver(this);
    //     mRegistry.add(newObserver);
    // }
    // 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<>();
 
    /**
     * Creates a new LifecycleRegistry for the given provider.
     * 

* You should usually create this inside your LifecycleOwner class's constructor and hold * onto the same instance. * * @param provider The owner LifecycleOwner */ public LifecycleRegistry(@NonNull LifecycleOwner provider) { mLifecycleOwner = new WeakReference<>(provider); mState = INITIALIZED; } /** * Moves the Lifecycle to the given state and dispatches necessary events to the observers. * * @param state new state * @deprecated Use {@link #setCurrentState(State)}. */ @Deprecated @MainThread public void markState(@NonNull State state) { setCurrentState(state); } /** * Moves the Lifecycle to the given state and dispatches necessary events to the observers. * * @param state new state */ @MainThread public void setCurrentState(@NonNull State state) { moveToState(state);ha } /** * Sets the current state and notifies the observers. *

* Note that if the {@code currentState} is the same state as the last call to this method, * calling this method has no effect. * * @param event The event that was received */ public void handleLifecycleEvent(@NonNull Lifecycle.Event event) { State next = getStateAfter(event); moveToState(next); } private void moveToState(State next) { if (mState == next) { return; } mState = next; if (mHandlingEvent || mAddingObserverCounter != 0) { mNewEventOccurred = true; // we will figure out what to do on upper level. return; } mHandlingEvent = true; sync(); mHandlingEvent = false; } private boolean isSynced() { if (mObserverMap.size() == 0) { return true; } State eldestObserverState = mObserverMap.eldest().getValue().mState; State newestObserverState = mObserverMap.newest().getValue().mState; return eldestObserverState == newestObserverState && mState == newestObserverState; } private State calculateTargetState(LifecycleObserver observer) { Entry<LifecycleObserver, ObserverWithState> previous = mObserverMap.ceil(observer); State siblingState = previous != null ? previous.getValue().mState : null; State parentState = !mParentStates.isEmpty() ? mParentStates.get(mParentStates.size() - 1) : null; return min(min(mState, siblingState), parentState); } @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); 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(); // mState / subling may have been changed recalculate targetState = calculateTargetState(observer); } if (!isReentrance) { // we do sync only on the top level. sync(); } mAddingObserverCounter--; } private void popParentState() { mParentStates.remove(mParentStates.size() - 1); } private void pushParentState(State state) { mParentStates.add(state); } @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); } /** * The number of observers. * * @return The number of observers. */ @SuppressWarnings("WeakerAccess") public int getObserverCount() { return mObserverMap.size(); } @NonNull @Override public State getCurrentState() { return mState; } 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); } 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); 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(); } } } // happens only on the top of stack (never in reentrance), // so it doesn't have to take in account parents private void sync() { LifecycleOwner lifecycleOwner = mLifecycleOwner.get(); if (lifecycleOwner == null) { throw new IllegalStateException("LifecycleOwner of this LifecycleRegistry is already" + "garbage collected. It is too late to change lifecycle state."); } 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<LifecycleObserver, ObserverWithState> newest = mObserverMap.newest(); if (!mNewEventOccurred && newest != null && mState.compareTo(newest.getValue().mState) > 0) { forwardPass(lifecycleOwner); } } mNewEventOccurred = false; } static State min(@NonNull State state1, @Nullable State state2) { return state2 != null && state2.compareTo(state1) < 0 ? state2 : state1; } 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; } } }

我们先来看下LifecycleRegister声明的属性:

mObserverMap: FastSafeIterableMap类型,FastSafeIterableMap是androidx包里面的一个容器类,这个类的特点是实现了在遍历过程中的安全增删元素。LifecycleObserver是订阅者,ObserverWithState则是对订阅者的封装。

mState: State类型,记录了被订阅者LifecycleOwner的当前状态

mLifecycleOwner: WeakReference类型,对应的LifecycleOwner的引用,被包装成了弱引用类型,防止内存泄漏,并且在添加Observer 和处理事件的时候都有判断LifecycleOwner是否有释放,如果被释放则不继续处理事件。

除此之外,LifecycleRegistry还有四个变量:mAddingObserverCounter(int)、mHandlingEvent(boolean)、mNewEventOccurred(boolean)、mParentStates(ArrayList);这四个变量都用于维护事件嵌套(在更新订阅者的过程中新增订阅者或者发送新事件)发生时LifecycleRegistry的状态维护

下面我们将从添加addObserver() 和 handleLifecycleEvent() 为分析入口进行解析

addObserver源码分析

  1. 第一步,将传入参数observer封装成一个ObserverWithState对象;这层封装有两个用处,第一,LifecycleObserver和它的子类有的是用注解,有的是用继承,ObserverWithState统一了它们的接口,方便调用。第二,ObserverWithState内部也保存了state,用于记录这个observer已经回调到的状态,防止重复调用;

  2. 第二步,将封装后的statefulObserver保存进以原始参数observer为key的map中去,同时判断是否这个observer之前已经添加过了,如果previous不为null,表示之前已经添加过了,就直接退出流程;如果lifecycleOwner为null,说明lifecycleOwner已经死亡了,那么也可以直接退出。

  3. 第三步,将新的订阅者加进订阅者列表之后,需要将它的状态同步到最新的状态mState。根据新的订阅者之前的状态和LifecycleRegistry当前的状态,算出当前Observer应该有的状态,然后使用while循环,一步步将当前Observer的状态变为应该有的状态,也就是说如果你添加监听者的时机比较晚,比如在onPause的时候添加的,那么你仍然会收到之前的状态。

接下来我们看下怎么使用ObserverWithState统一回调接口的

ObserverWithState的工作原理

在ObserverWithState 构造方法的时候,使用 Lifecycling.lifecycleEventObserver(observer) 方法进行转换

static LifecycleEventObserver lifecycleEventObserver(Object object) {
    boolean isLifecycleEventObserver = object instanceof LifecycleEventObserver;
    boolean isFullLifecycleObserver = object instanceof FullLifecycleObserver;
     
    //如果你的Observer直接实现FullLifecycleObserver,则直接使用FullLifecycleObserverAdapter封装,后面分发onStateChanged的时候在里面直接根据event类型回调相应方法
    if (isLifecycleEventObserver && isFullLifecycleObserver) {
        return new FullLifecycleObserverAdapter((FullLifecycleObserver) object,
                (LifecycleEventObserver) object);
    }
    //同上
    if (isFullLifecycleObserver) {
        return new FullLifecycleObserverAdapter((FullLifecycleObserver) object, null);
    }
 
    //如果你的Observer实现LifecycleEventObserver,则直接使用该Observer进行事件分发
    if (isLifecycleEventObserver) {
        return (LifecycleEventObserver) object;
    }
 
    //如果不是上面的情况,则判断是使用反射还是使用生成的方法直接调用
    final Class<?> klass = object.getClass();
    int type = getObserverConstructorType(klass);
    //根据返回的回调类型来生成对应的Observer适配器
    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);
    }
    return new ReflectiveGenericLifecycleObserver(object);
}
 
 
 
//获取当前类的构造函数类型
private static int getObserverConstructorType(Class<?> klass) {
    Integer callbackCache = sCallbackCache.get(klass);
    if (callbackCache != null) {
        return callbackCache;
    }
    int type = resolveObserverCallbackType(klass);
    sCallbackCache.put(klass, type);
    return type;
}
 
private static int resolveObserverCallbackType(Class<?> klass) {
    // anonymous class bug:35073837
    //匿名内部类直接返回getCanonicalName返回的是null,直接返回反射回调类型
    if (klass.getCanonicalName() == null) {
        return REFLECTIVE_CALLBACK;
    }
 
    //获取生成的构造方法
    Constructor<? extends GeneratedAdapter> constructor = generatedConstructor(klass);
    if (constructor != null) {
        //如果存在生成的构造方法,则直接返回生成的代码回调类型
        //考虑什么情况会不存在构造方法?  比如一个类实现了MySimpleLifecycleObserver LifecycleObserver,里面通过注解监听了生命周期方法,然后另外一个类直接继承 MySimpleLifecycleObserver, 里面没有任何逻辑,则该类不会生成对应构造方法
        sClassToAdapters.put(klass, Collections
                .<Constructor<? extends GeneratedAdapter>>singletonList(constructor));
        return GENERATED_CALLBACK;
    }
 
    //没存在生成的构造方法,比如没有使用apt,则直接返回反射回调类型
    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;
}
 
 
class FullLifecycleObserverAdapter implements LifecycleEventObserver {
 
    private final FullLifecycleObserver mFullLifecycleObserver;
    private final LifecycleEventObserver mLifecycleEventObserver;
 
    FullLifecycleObserverAdapter(FullLifecycleObserver fullLifecycleObserver,
            LifecycleEventObserver lifecycleEventObserver) {
        mFullLifecycleObserver = fullLifecycleObserver;
        mLifecycleEventObserver = lifecycleEventObserver;
    }
 
    //里面直接根据事件调用相应回调方法,逻辑比较简单
    @Override
    public void onStateChanged(@NonNull LifecycleOwner source, @NonNull Lifecycle.Event event) {
        switch (event) {
            case ON_CREATE:
                mFullLifecycleObserver.onCreate(source);
                break;
            case ON_START:
                mFullLifecycleObserver.onStart(source);
                break;
            case ON_RESUME:
                mFullLifecycleObserver.onResume(source);
                break;
            case ON_PAUSE:
                mFullLifecycleObserver.onPause(source);
                break;
            case ON_STOP:
                mFullLifecycleObserver.onStop(source);
                break;
            case ON_DESTROY:
                mFullLifecycleObserver.onDestroy(source);
                break;
            case ON_ANY:
                throw new IllegalArgumentException("ON_ANY must not been send by anybody");
        }
        if (mLifecycleEventObserver != null) {
            mLifecycleEventObserver.onStateChanged(source, event);
        }
    }
}
 
 
public interface LifecycleEventObserver extends LifecycleObserver {
    /**
     * Called when a state transition event happens.
     *
     * @param source The source of the event
     * @param event The event
     */
    void onStateChanged(@NonNull LifecycleOwner source, @NonNull Lifecycle.Event event);
}
 
 
//单个构造方法Observer适配器
class SingleGeneratedAdapterObserver implements LifecycleEventObserver {
 
    private final GeneratedAdapter mGeneratedAdapter;
 
    SingleGeneratedAdapterObserver(GeneratedAdapter generatedAdapter) {
        mGeneratedAdapter = generatedAdapter;
    }
 
    @Override
    public void onStateChanged(@NonNull LifecycleOwner source, @NonNull Lifecycle.Event event) {
        mGeneratedAdapter.callMethods(source, event, false, null);
        mGeneratedAdapter.callMethods(source, event, true, null);
    }
}
 
 
//多个构造方法Observer适配器
class CompositeGeneratedAdaptersObserver implements LifecycleEventObserver {
 
    private final GeneratedAdapter[] mGeneratedAdapters;
 
    CompositeGeneratedAdaptersObserver(GeneratedAdapter[] generatedAdapters) {
        mGeneratedAdapters = generatedAdapters;
    }
 
    @Override
    public void onStateChanged(@NonNull LifecycleOwner source, @NonNull Lifecycle.Event event) {
        MethodCallsLogger logger = new MethodCallsLogger();
        for (GeneratedAdapter mGenerated: mGeneratedAdapters) {
            mGenerated.callMethods(source, event, false, logger);
        }
        for (GeneratedAdapter mGenerated: mGeneratedAdapters) {
            mGenerated.callMethods(source, event, true, logger);
        }
    }
}
 
 
//反射Observer适配器
class ReflectiveGenericLifecycleObserver implements LifecycleEventObserver {
    private final Object mWrapped;
    private final CallbackInfo mInfo;
 
    ReflectiveGenericLifecycleObserver(Object wrapped) {
        mWrapped = wrapped;
        //生成反射回调信息
        mInfo = ClassesInfoCache.sInstance.getInfo(mWrapped.getClass());
    }
 
    @Override
    public void onStateChanged(@NonNull LifecycleOwner source, @NonNull Event event) {
        //调用相应反射方法
        mInfo.invokeCallbacks(source, event, mWrapped);
    }
 
 
    //CallbackInfo中的代码,放到这方便理解 可以看到也是每次都是分发对应生命周期事件和ON_ANY事件
    void invokeCallbacks(LifecycleOwner source, Lifecycle.Event event, Object target) {
        invokeMethodsForEvent(mEventToHandlers.get(event), source, event, target);
        invokeMethodsForEvent(mEventToHandlers.get(Lifecycle.Event.ON_ANY), source, event,
            target);
    }
}

可以看到先判断的是 LifecycleEventObserver 和 FullLifecycleObserver,如果你的Observer实现了FullLifecycleObserver,那么直接使用 FullLifecycleObserverAdapter进行封装,后面调用onStateChanged分发事件的时候再根据事件类型分发到对应方法中。

如果只实现了LifecycleEventObserver,就直接返回该对象,后面事件分发的时候直接就调用了其 onStateChanged 方法,这也能解释上面说的为什么加注解方法并不会执行的原因。

后面是判断回调是使用生成代码回调还是使用反射回调,如果使用了apt可能就是调用生成的代码相应的方法,如果没有,那最终就是使用反射(具体看上面代码中注释逻辑)

可以看到,最终是通过Observer适配器进行的事件分发

Observer适配器有5种 (名字我个人这么叫的,方便理解和记忆)

  • 全生命周期Observer适配器 FullLifecycleObserverAdapter
  • 状态Observer适配器 LifecycleEventObserver
  • 单构造方法Observer适配器 SingleGeneratedAdapterObserver
  • 多构造方法Observer适配器 CompositeGeneratedAdaptersObserver
  • 反射Observer适配器 ReflectiveGenericLifecycleObserver

从代码逻辑和性能上面分析来讲,google还是推荐使用第一种,也就是使用 DefaultLifecycleObserver

handleLifecycleEvent源码分析

根据上面的源码分析,我们总结为以下几个步骤

  1. 首先更新当前LifecycleRegistry mState的状态
  2. 然后判断当前是否在处理事件同步的过程中,如果是,则标记mNewEventOccurred为true,
  3. sync过程中会判断当前是否有新事件来通过事件是一个while循环,isSyncd()方法判断mObserverMap中最老的观察者和最新的观察者及当前的状态是否一致,如果一致,则说明同步完成,如果不一致,继续while循环
  4. sync过程中判断LifecycleRegistry当前的状态,如果比第一个Observer的状态小,则调用backwardPass方法将所有的observer的状态都往后倒退,并且是根据状态一步步倒退,而不是直接回到当前的状态,所以observer收到的生命周期事件已经是连续的
  5. 如果LifecycleRegistry当前状态,比最后一个Observer的状态还大,则调用forwardPass方法将所有的observer的状态都往前进,并且是根据状态一步步前进。
  6. 在倒退或前进的过程中,对事件进行分发,调用mObserverMap中存储的ObserverWithState的dispatchEvent分发,最终调用上面封装好的Observer适配器的onStateChanged方法进行分发

需要注意的是:Lifecycle的使用要放在主线程中调用,源码中也有体现,方法上面加了 @MainThread 注解, 并且代码内部并没有进行加锁或线程同步操作,所以开发过程中要保持主线程调用。

至此,Lifecycle相应的使用和源码分析已经结束。

官方文档

参考资料:

https://blog.csdn.net/xfhy_/article/details/88543884

https://blog.csdn.net/quiet_olivier/article/details/103384146

https://www.imooc.com/article/298283

你可能感兴趣的:(Android,Lifecycle)