前言

我们在使用 activity、 fregment, 在或者使用 ViewModel 等好多组件都会涉及到 lifecycle。 我们可以通过 lifecycle 去感知到生命周期。 非常多得使用, 所以还是很有必要了解一下的。

基本使用

1
2
3
4
lifecycle.addObserver(object : LifecycleEventObserver  {
override fun onStateChanged(source: LifecycleOwner, event: Lifecycle.Event) {
}
})

我们拿到 lifecycle 后就可以添加一个回调, 就可以很容易的获取到组件的生命周期了。 其中 event 对应的就是各个生命周期的一个枚举而已, 就不再多贴代码了。
我们主要看下它是怎么感知到组件的生命周期的呢。

源码分析

1
2
3
4
5
6
// ComponentActivity
public Lifecycle getLifecycle() {
return mLifecycleRegistry;
}

private final LifecycleRegistry mLifecycleRegistry = new LifecycleRegistry(this);

可以看到 Activity 中的 lifecycle 是一个 LifecycleRegistry 对象。 我们关心 onStateChanged 是在哪里调用的呢。 肯定是 mLifecycleRegistry 操作调用了。 但是从各个 ComponentActivity 源码里竟然没有找到其使用及调用。 不会是玄学的, 所以满满找找分析下。
其实 ComponentActivity 很简单, 我们看看 onCreate

1
2
3
4
5
6
7
8
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mSavedStateRegistryController.performRestore(savedInstanceState);
ReportFragment.injectIfNeededIn(this);
if (mContentLayoutId != 0) {
setContentView(mContentLayoutId);
}
}

多了一个 ReportFragment, 当你点进去的时候就会恍然大悟。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
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
LifecycleCallbacks.registerIn(activity);
}
// 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);
}
}
}

也就是在 Activity 中添加了一个 fragment, 即 tag 为 REPORT_FRAGMENT_TAG 的 ReportFragment。 然后 fragment 的生命周期调用了 dispath 去分发生命周期。 我们可以看到内部的判断, 一个是 instanceof LifecycleRegistryOwner, 一个是 LifecycleOwner。 那么他们有什么区别呢。
我们可以看到如果是 LifecycleRegistryOwner 的话, 就直接返回了, 我们通过上面的分析也可以知道, activity 中的变量就是 LifecycleRegistryOwner 这个玩意。 那么 LifecycleOwner 是啥呢。 这个通过其类的注释也明显, 不信你点进去自己看看。 这个就是我们除了 Activity 外自己设计组件或者什么自己去定义生命周期的回调。 这个统一了, 我们自己的设计的组件也就可以直接嫁接过来直接使用 lifecycle 这一套。 比如 ViewModel 等。