Jetpack之生命周期感知组件-Lifecycle原理篇

2021年02月28日 99 字 Jetpack


上一篇文章中我们讲了Jetpack之生命周期感知组件-Lifecycle使用篇,接下来我们来看一下他是如何工作的吧。

在了解其工作原理前,我们需要先简单了解以下ActivityThread对Activity生命周期的分发流程,以便理解Lifecycle的工作原理。

此篇前半部分将讲述API26及API30生命周期分发流程,后半部分依照前半部分对照讲述Lifecycle生命周期分发时机,最后将介绍Lifecycle源码执行流程及ProcessLifecycleOwner是如何实现应用前后台监听的。

生命周期的产生及分发

此部分源码取自Android SDK api26 & api30, 获取方式为使用Android Studio 的 SDK Manager 下载 api26 及 api30 源代码,源代码目录为 %AndroidSDK%/source/android-版本号,你可以使用SublimeText等工具打开源码对照阅读。

Lifecycle以Api29为分界点有不同的处理方式,这是先讲述此节内容的原因,此处以Api26及Api30为代表讲述。

API 26

我们知道,Activity是由ActivityThread生成及管理的。此处以ActivityThread.performLaunchActivity()为起点,分析Activity onCreate()/onStart()事件的产生及分发。

我们先看简化版的performLaunchActivity()代码:

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
35
36
37
@link{ActivityThread}
private Activity performLaunchActivity(ActivityClientRecord r, Intent customIntent) {
// do something create Activity
activity = mInstrumentation.newActivity(
cl, component.getClassName(), r.intent);
// ... init Activity
try {
Application app = r.packageInfo.makeApplication(false, mInstrumentation);
// logs
if (activity != null) {
// activity attach & setTheme ...
activity.mCalled = false;
if (r.isPersistable()) {
// onCreate()
mInstrumentation.callActivityOnCreate(activity, r.state, r.persistentState);
} else {
mInstrumentation.callActivityOnCreate(activity, r.state);
}
// some log
r.activity = activity;
r.stopped = true;
if (!r.activity.mFinished) {
// onStart()
activity.performStart();
r.stopped = false;
}
// do something
}
// do something
} catch (SuperNotCalledException e) {
throw e;

} catch (Exception e) {
// log error
}
return activity;
}

我们看到,在完成了Activity启动条件后调用了mInstrumentation.callActivityOnCreate(activity.performStart()( 即生命周期onCreate()和onStart()), 为了一并了解Fragment生命周期的分发,我们以onStart()为例,onStart()事件产生于此,我们继续跟进 activity.performStart() :

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
@link{Activity}
final void performStart() {
// do something
// 注意此处,会回调到activity.onStart();
mInstrumentation.callActivityOnStart(this);
// logs

// 注意此处mFragments是 FragmentController,
// 后续会调用FragmentManager.dispatchStart()、fragment.performStart()
// 最终执行到 fragment.onStart()
mFragments.dispatchStart();
mFragments.reportLoaderStart();

// do Something others

mActivityTransitionState.enterReady(this);
}

@link{Instrumentation}
public void callActivityOnStart(Activity activity) {
activity.onStart();
}

由上面代码代码我们了解了API26时 Activity的onStart()事件的产生到传递,以及传递给Fragment的方式【此处代码跟进省略,但应了解这个流程,后续在讲述Lifecycle时将会用到】。

API 30 (API lvl ≥ 29)

同样的,此处以ActivityThread.performLaunchActivity()为起点,分析Activity onCreate()/onStart()事件的产生及分发:

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
@link{ActivityThread}
private Activity performLaunchActivity(ActivityClientRecord r, Intent customIntent) {

// create Activity
activity = mInstrumentation.newActivity(
cl, component.getClassName(), r.intent);

try {
Application app = r.packageInfo.makeApplication(false, mInstrumentation);
// init Activity & setTheme
activity.mCalled = false;
if (r.isPersistable()) {
// onCreate()
mInstrumentation.callActivityOnCreate(activity, r.state, r.persistentState);
} else {
mInstrumentation.callActivityOnCreate(activity, r.state);
}
// some log
r.activity = activity;
mLastReportedWindowingMode.put(activity.getActivityToken(),
config.windowConfiguration.getWindowingMode());
// 设置生命周期
r.setState(ON_CREATE);
// something
} catch (SuperNotCalledException e) {
throw e;

} catch (Exception e) {
// log error
}

return activity;
}

上述代码与 API 26 基本一致,但是此时onCreate事件与onStart事件的产生已不是耦合相关,同样的关注onStart()生命周期,此处已不包含onStart()相关的代码及调用,我们发现有新的代码r.setState(ON_CREATE);可能与生命周期有关,猜测是否onStart()事件也会有类似方法,果然,在相邻的下一个方法handleStartActivity中我们发现类似代码:

1
2
3
4
5
6
7
8
9
10
11
12
@link{ActivityThread}
public void handleStartActivity(IBinder token, PendingTransactionActions pendingActions) {
// do something
// Start
activity.performStart("handleStartActivity");
r.setState(ON_START);

// something Restore instance state

updateVisibility(r, true /* show */);
mSomeActivitiesChanged = true;
}

类似的,这里调用了activity.performStart("handleStartActivity");

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
@link{Activity}
final void performStart(String reason) {
// 注意注意
// 注意此处有新代码,用以通知注册在Application及Activity中的ActivityLifecycleCallbacks当前的生命周期状态,由这些回调方法分发生命周期事件
dispatchActivityPreStarted();
// do something
// 最终调用onStart()
mInstrumentation.callActivityOnStart(this);
// something
// 注意此处mFragments是 FragmentController,
// 后续会调用FragmentManager.dispatchStart()、fragment.performStart()
// 最终执行到 fragment.onStart()
mFragments.dispatchStart();
mFragments.reportLoaderStart();

// do something debug

mActivityTransitionState.enterReady(this);

// 注意注意
// 注意此处有新代码,用以通知注册在Application及Activity中的ActivityLifecycleCallbacks当前的生命周期状态,由这些回调方法分发生命周期事件
dispatchActivityPostStarted();
}

@link{Instrumentation}
public void callActivityOnStart(Activity activity) {
activity.onStart();
}

此处主体逻辑与API 26一致,均是调用Activity onStart()回调和分发事件给Fragment,我们注意到此处多了两个 “dispatchActivityXXX()” 方法,跟进这两个 “dispatchActivityXXX()” 方法,均为执行以下类似代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
@link{Activity}
private void dispatchActivityPreStarted() {
getApplication().dispatchActivityPreStarted(this);
Object[] callbacks = collectActivityLifecycleCallbacks();
if (callbacks != null) {
for (int i = 0; i < callbacks.length; i++) {
((Application.ActivityLifecycleCallbacks) callbacks[i]).onActivityPreStarted(this);
}
}
}

@link{Application}
/* package */ void dispatchActivityPreStarted(@NonNull Activity activity) {
Object[] callbacks = collectActivityLifecycleCallbacks();
if (callbacks != null) {
for (int i = 0; i < callbacks.length; i++) {
((ActivityLifecycleCallbacks) callbacks[i]).onActivityPreStarted(activity);
}
}
}

简单分析代码,可以发现,其主要功能是将不同的生命周期事件上报给Applicaiton进行回调分发以及通知注册在Activity中的回调分发【记住此处,与Lifecycle在Api29前后不同处理方式有关】。

而相比于 API26,通过跟进collectActivityLifecycleCallbacks()发现, Activity在API29之后新增了生命周期注册功能,即维护了一个 ActivityLifecycleCallbacks集合,而生命周期在Activity中的最后使命就是通过 dispatchActivityXXX() 向注册在Activity/Application中的 ActivityLifecycleCallbacks 分发事件。

Lifecycle源码解析

前半部分,我们讲述了Activity生命周期事件的产生和分发,接下来我们来看一下Lifecycle是如何订阅和消费这些事件的吧。

Lifecycle

首先我们来看一下Lifecycle的代码:

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
35
36
37
public abstract class Lifecycle {

@MainThread
public abstract void addObserver(@NonNull LifecycleObserver observer);

@MainThread
public abstract void removeObserver(@NonNull LifecycleObserver observer);

@MainThread
@NonNull
public abstract State getCurrentState();

@SuppressWarnings("WeakerAccess")
public enum Event {
ON_CREATE,
ON_START,
ON_RESUME,
ON_PAUSE,
ON_STOP,
ON_DESTROY,
ON_ANY;
// some apis
}

@SuppressWarnings("WeakerAccess")
public enum State {
DESTROYED,
INITIALIZED,
CREATED,
STARTED,
RESUMED;

public boolean isAtLeast(@NonNull State state) {
return compareTo(state) >= 0;
}
}
}

Lifecycle 是一个类,用于存储有关组件(如 Activity 或 Fragment)的生命周期状态的信息,并允许其他对象观察此状态。
Lifecycle 使用两种主要枚举跟踪其关联组件的生命周期状态:

  • 事件
     从框架和 Lifecycle 类分派的生命周期事件。这些事件映射到 Activity 和 Fragment 中的回调事件。
    
  • 状态
     由 Lifecycle 对象跟踪的组件的当前状态。 
    

Lifecycle.png

Lifecycle的主要子类是LifecycleRegistry,主要用于最终处理和分发事件给对应的Observer,由于其在调用流程的最尾端,故我们放到后面流程中一起讲解。

ComponentActivity

支持库 26.1.0 及更高版本中的 Fragment 和 Activity 已实现 LifecycleOwner 接口。

官方文档有指出支持库 26.1.0以上的Fragment和Activity中已实现LifecycleOwner 接口,我们从androidx.appcompat.app.AppCompatActivity向上找寻LifecycleOwner的身影,androidx.activity.ComponentActivityandroidx.core.app.ComponentActivity均有对 LifecycleOwner的实现,我们先看下父类androidx.core.app.ComponentActivity中的处理:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
public class ComponentActivity extends Activity implements
LifecycleOwner,
KeyEventDispatcher.Component {
private LifecycleRegistry mLifecycleRegistry = new LifecycleRegistry(this);

@SuppressLint("RestrictedApi")
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ReportFragment.injectIfNeededIn(this);
}

@CallSuper
@Override
protected void onSaveInstanceState(@NonNull Bundle outState) {
mLifecycleRegistry.markState(Lifecycle.State.CREATED);
super.onSaveInstanceState(outState);
}
// others
}

我们发现,其代码不多,与生命周期相关的核心代码仅实现了onCreate及onSaveInstanceState,其中onCreate()中中仅有一句特别的代码ReportFragment.injectIfNeededIn(this);我们有理由相信他与生命周期管理有关,我们尝试跟进一下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
@link{ReportFragment}
public static void injectIfNeededIn(Activity activity) {
if (Build.VERSION.SDK_INT >= 29) {
// 在API 29+上,我们可以直接注册正确的生命周期回调
LifecycleCallbacks.registerIn(activity);
}
// 之前的API 29和保持与旧版本的兼容性
// ProcessLifecycleOwner(当生命周期运行时更新时可能不会更新,
// 并且需要支持不从支持库的FragmentActivity扩展的活动),
// 使用框架片段来获得生命周期事件的正确时间
android.app.FragmentManager manager = activity.getFragmentManager();
if (manager.findFragmentByTag(REPORT_FRAGMENT_TAG) == null) {
manager.beginTransaction().add(new ReportFragment(), REPORT_FRAGMENT_TAG).commit();
// 希望我们是第一个达成交易的。
manager.executePendingTransactions();
}
}

果不其然,我们发现这里有LifecycleCallbacks关键字,还记得前面讲到的生命周期分发流程中提到的API不同版本对于生命周期处理方式的不同吗,主要区别在于API29 Activity中新增了ActivityLifecycleCallbacks的注册和分发,而API 29之前生命周期均会传递给Fragment。 此处我们发现这里的 ReportFragment 本质是一个Fragment,在Activity创建(onCreate)的时候:

  • 对于API ≥ 29 将会注册生命周期回调,并将ReportFragment添加到Activity中
  • 对于API < 29 将ReportFragment添加到Activity中.

那么这样做的意义是什么呢,我们来看一下这里injectIfNeededIn具体干了什么。
首先 LifecycleCallbacks.registerIn(activity):

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
35
36
37
38
39
40
41
@RequiresApi(29)
static class LifecycleCallbacks implements Application.ActivityLifecycleCallbacks {

static void registerIn(Activity activity) {
activity.registerActivityLifecycleCallbacks(new LifecycleCallbacks());
}

@Override
public void onActivityPostCreated(@NonNull Activity activity,
@Nullable Bundle savedInstanceState) {
dispatch(activity, Lifecycle.Event.ON_CREATE);
}

@Override
public void onActivityPostStarted(@NonNull Activity activity) {
dispatch(activity, Lifecycle.Event.ON_START);
}

@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 onActivityPreStopped(@NonNull Activity activity) {
dispatch(activity, Lifecycle.Event.ON_STOP);
}

@Override
public void onActivityPreDestroyed(@NonNull Activity activity) {
dispatch(activity, Lifecycle.Event.ON_DESTROY);
}

// ignore empty function
}

这里将会把一个 Application.ActivityLifecycleCallbacks 注册到当前Activity中,还记得前面讲到的,生命周期在Activity中的最后使命就是通过 dispatchActivityXXX() 向注册在Activity/Application中的 ActivityLifecycleCallbacks 分发事件。
对应此处,即是生命周期事件会反馈到 ReportFragment.LifecycleCallbacks 并最终调用dispatch(activity, Lifecycle.Event.ON_XXXX);分发。

那么在API29以前呢??

前面有要求注意过 在生命周期分发过程中 均会调用 FragmentController.dispatchXXX(); 方法,最终会调用Fragment的 onXXXX()方法,我们有理由相信在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
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP_PREFIX)
public class ReportFragment extends android.app.Fragment {
private static final String REPORT_FRAGMENT_TAG = "androidx.lifecycle"
+ ".LifecycleDispatcher.report_fragment_tag";

public static void injectIfNeededIn(Activity activity) {
// 见上一codepod
}

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

// private ActivityInitializationListener mProcessListener;

@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) {
//只在API 29之前的API级别上从ReportFragment分派事件。在API 29+中,
//这是由reportfragment . injectifneeddin中添加的ActivityLifecycleCallbacks处理的
dispatch(getActivity(), event);
}
}
}

果然,验证了我们的猜想,并从 dispatch() 中的代码注释我们可知:

只在API 29之前的API级别上从ReportFragment分派事件。在API 29+中,这是由reportfragment . injectifneeddin中添加的ActivityLifecycleCallbacks处理的

这句话基本总结了ReportFragment在生命周期事件分发过程中的扮演的角色,结合前面讲的生命周期事件分发,我们对于生命周期事件传递到分发给具体的Lifecycle们的流程基本已经清晰了:

  • ActivityThread产生生命周期事件并通过Instrumentation和Activity传递或调用 Activity.onXXX()
  • Activity创建时(onCreate)会被注入ReportFragment,而ReportFragment负责将生命周期事件分发给对应的Lifecycle
  • API29及以上时,Activity在处理生命周期时会通知 Application 处理生命周期回调且自身也同样处理生命周期回调,API29以上这些回调将会被ReportFragment接收,而API29以下则由FragmentController直接分发给ReportFragment。

那么我们就剩下一个问题了,ReportFragment分发事件是如何到达我们注册的LifecycleObserver的?

dispatch(Activity, Lifecycle.Event);

我们继续跟进ReportFragment中最终分发的方法dispatch(Activity, Lifecycle.Event):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
@link{ReportFragment}
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);
}
}
}

这里都会调用LifecycleRegistry.handleLifecycleEvent(Lifecycle.Event event)方法,我们继续跟进:

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
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
public void handleLifecycleEvent(@NonNull Lifecycle.Event event) {
enforceMainThreadIfNeeded("handleLifecycleEvent");
moveToState(event.getTargetState());
}

private void moveToState(State next) {
// something。。。
sync();
// code
}

private void sync() {
// something
if (mState.compareTo(mObserverMap.eldest().getValue().mState) < 0) {
backwardPass(lifecycleOwner);
}
// something
if (!mNewEventOccurred && newest != null
&& mState.compareTo(newest.getValue().mState) > 0) {
forwardPass(lifecycleOwner);
}

}

private void backwardPass(LifecycleOwner lifecycleOwner) {
// // something
observer.dispatchEvent(lifecycleOwner, event);
}

private void forwardPass(LifecycleOwner lifecycleOwner) {
// something
observer.dispatchEvent(lifecycleOwner, event);
}

static class ObserverWithState {
State mState;
LifecycleEventObserver mLifecycleObserver;

ObserverWithState(LifecycleObserver observer, State initialState) {
// 注意此处,此处在初始化时,会调用此方法,读取LifecycleObserver中的运行时
// 注解@OnLifecycleEvent,为后续反射方法做准备
mLifecycleObserver = Lifecycling.lifecycleEventObserver(observer);
mState = initialState;
}

void dispatchEvent(LifecycleOwner owner, Event event) {
State newState = event.getTargetState();
mState = min(mState, newState);
mLifecycleObserver.onStateChanged(owner, event);
mState = newState;
}
}

我们发现,无论如何,最终都会走到(ObserverWithState)observer.dispatchEvent(lifecycleOwner, event), 即最终调用LifecycleObserver.onStateChanged(owner, event)

1
2
3
public interface LifecycleEventObserver extends LifecycleObserver {
void onStateChanged(@NonNull LifecycleOwner source, @NonNull Lifecycle.Event event);
}

我们 通过Go to implementation(s) 快捷键 【如有不清楚快捷键的,请打开 File -> Settings -> Keymap 搜索 Go to implementation(s)】 查看其实现以跟进其流程。
我们以 反射通用生命周期观察器 ReflectiveGenericLifecycleObserver 为例继续跟进:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
// 命名直译为 反射通用生命周期观察器
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 去执行Callback :

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
35
36
37
38
39
40
41
42
43
44
45
static class CallbackInfo {
// something

@SuppressWarnings("ConstantConditions")
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);
}

private static void invokeMethodsForEvent(List<MethodReference> handlers,
LifecycleOwner source, Lifecycle.Event event, Object mWrapped) {
if (handlers != null) {
for (int i = handlers.size() - 1; i >= 0; i--) {
handlers.get(i).invokeCallback(source, event, mWrapped);
}
}
}
}

static final class MethodReference {
// something

void invokeCallback(LifecycleOwner source, Lifecycle.Event event, Object target) {
//noinspection TryWithIdenticalCatches
try {
switch (mCallType) {
case CALL_TYPE_NO_ARG:
mMethod.invoke(target);
break;
case CALL_TYPE_PROVIDER:
mMethod.invoke(target, source);
break;
case CALL_TYPE_PROVIDER_WITH_EVENT:
mMethod.invoke(target, source, event);
break;
}
} catch (InvocationTargetException e) {
throw new RuntimeException("Failed to call observer method", e.getCause());
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
}
}
// something
}

从上面代码我们可以了解到,CallbackInfo.invokeCallbacks 最终调用 MethodReference.invokeCallback() 通过反射完成最终调用,其实至此,整个流程就以完结。

但是!!!

此时有一个疑问,这些这里反射使用的方法是哪里获取的,为什么他能找到我们添加了@OnLifecycleEvent注解的方法???

来,让我们反向查找一下, 既然他用了CallbackInfo,我们来找找从哪里创建了CallbackInfo,我们仔细寻找一下 CallbackInfo所在的class文件,嘿,就在内部类 CallbackInfo定义的上面一行~:

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
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
private CallbackInfo createInfo(Class<?> klass, @Nullable Method[] declaredMethods) {
Class<?> superclass = klass.getSuperclass();
Map<MethodReference, Lifecycle.Event> handlerToEvent = new HashMap<>();
if (superclass != null) {
CallbackInfo superInfo = getInfo(superclass);
if (superInfo != null) {
handlerToEvent.putAll(superInfo.mHandlerToEvent);
}
}

Class<?>[] interfaces = klass.getInterfaces();
for (Class<?> intrfc : interfaces) {
for (Map.Entry<MethodReference, Lifecycle.Event> entry : getInfo(
intrfc).mHandlerToEvent.entrySet()) {
verifyAndPutHandler(handlerToEvent, entry.getKey(), entry.getValue(), klass);
}
}
// 获取class中的方法
Method[] methods = declaredMethods != null ? declaredMethods : getDeclaredMethods(klass);
boolean hasLifecycleMethods = false;
// 遍历方法
for (Method method : methods) {
// 拿到方法的OnLifecycleEvent注解
OnLifecycleEvent annotation = method.getAnnotation(OnLifecycleEvent.class);
if (annotation == null) {
continue;
}
hasLifecycleMethods = true;
Class<?>[] params = method.getParameterTypes();
int callType = CALL_TYPE_NO_ARG;
if (params.length > 0) {
callType = CALL_TYPE_PROVIDER;
if (!params[0].isAssignableFrom(LifecycleOwner.class)) {
throw new IllegalArgumentException(
"invalid parameter type. Must be one and instanceof LifecycleOwner");
}
}
// 获取关注的生命周期事件
Lifecycle.Event event = annotation.value();

if (params.length > 1) {
callType = CALL_TYPE_PROVIDER_WITH_EVENT;
if (!params[1].isAssignableFrom(Lifecycle.Event.class)) {
throw new IllegalArgumentException(
"invalid parameter type. second arg must be an event");
}
if (event != Lifecycle.Event.ON_ANY) {
throw new IllegalArgumentException(
"Second arg is supported only for ON_ANY value");
}
}
if (params.length > 2) {
throw new IllegalArgumentException("cannot have more than 2 params");
}
// 封装成MethodReference以待使用
MethodReference methodReference = new MethodReference(callType, method);
// 校验及存储 MethodReference
verifyAndPutHandler(handlerToEvent, methodReference, event, klass);
}
// 封装成 CallbackInfo 以待使用
CallbackInfo info = new CallbackInfo(handlerToEvent);
// 存储 CallbackInfo
mCallbackMap.put(klass, info);
mHasLifecycleMethods.put(klass, hasLifecycleMethods);
return info;
}

代码一箩筐,看起来吓人,实际几句话,我们简单解释一下步骤:

  • 获取class中的方法 【此处class实为我们定义的LifecycleObserver,来自于addObserver】
  • 遍历方法
    • 拿到方法的OnLifecycleEvent注解
    • 获取关注的生命周期事件
    • 封装成MethodReference以待使用
    • 校验及存储 MethodReference
  • 封装成 CallbackInfo 以待使用
  • 存储 CallbackInfo

我们继续关注,是哪里调用他的呢??

向前向前:ClassesInfoCache.hasLifecycleMethods()
继续向前:Lifecycling.resolveObserverCallbackType()
-> Lifecycling.getObserverConstructorType()
-> Lifecycling.lifecycleEventObserver()

嘿,似乎有点眼熟,没错,在前面流程中调用 LifecycleRegistry.ObserverWithState.dispatchEvent()时,它的构造方法中我们见过这段代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
@link{LifecycleRegistry.ObserverWithState}
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 = event.getTargetState();
mState = min(mState, newState);
mLifecycleObserver.onStateChanged(owner, event);
mState = newState;
}
}

我们查找它的调用时机发现,在 addObserver中有调用其初始化:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
public void addObserver(@NonNull LifecycleObserver observer) {
enforceMainThreadIfNeeded("addObserver");
State initialState = mState == DESTROYED ? DESTROYED : INITIALIZED;
// 创建 ObserverWithState
ObserverWithState statefulObserver = new ObserverWithState(observer, initialState);
ObserverWithState previous = mObserverMap.putIfAbsent(observer, statefulObserver);
// something
statefulObserver.dispatchEvent(lifecycleOwner, event);
// something

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

至此,我们的整个流程算是完全走通了:

注册时addObserver

  • 编写LifecycleObserver并通过 Lifecycle.addObserver方法将观察者注册到LifecycleRegistry
  • LifecycleRegistry通过 ObserverWithState 调用 Lifecycling 最终通过反射获取LifecycleObserver中关注生命周期的方法和关注的生命周期,封装成MethodReference和CallbackInfo并缓存
  • ObserverWithState.dispatchEvent() 分发当前生命周期事件

生命周期变化时

  • ActivityThread通知Activity,Activity(无论何种方式)通知 ReportFragment
  • ReportFragment调用 LifecycleRegistry.handleLifecycleEvent(event)
  • LifecycleRegistry经过 moveToState() -> sync() -> backwardPass()/forwardPass() 最终调用ObserverWithState.dispatchEvent()
  • ObserverWithState.dispatchEvent() 调用LifecycleObserver.onStateChanged() 通知 CallbackInfo 通过反射执行对应方法
  • CallbackInfo.invokeCallbacks()查找到对应生命周期的 MethodReference 缓存,通过Method.invoke()调用,最终执行LifecycleObserver中关注对应生命周期的方法。

我们整理一下画一个时序图:

Lifecycle时序图.png

附 - ProcessLifecycleOwner是如何实现应用前后台监听

在 lifecycle-process.aar中存在AndroidManifest.xml文件,其中注册了一个provider组件:

1
2
3
4
5
6
7
<application>
<provider
android:name="androidx.lifecycle.ProcessLifecycleOwnerInitializer"
android:authorities="${applicationId}.lifecycle-process"
android:exported="false"
android:multiprocess="true" />
</application>
1
2
3
4
5
6
7
8
9
10
@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP_PREFIX)
public class ProcessLifecycleOwnerInitializer extends ContentProvider {
@Override
public boolean onCreate() {
LifecycleDispatcher.init(getContext());
ProcessLifecycleOwner.init(getContext());
return true;
}
// others
}

这个组件在创建时机在应用启动时,其onCreate中做了两件事:

  • LifecycleDispatcher.init(getContext()) 向Application中注册生命周期事件监听
  • ProcessLifecycleOwner.init(getContext()) 向ProcessLifecycleOwner中绑定Application,且为ReportFragment添加ActivityInitializationListener。
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
35
36
37
38
39
40
41
42
43
44
45
void attach(Context context) {
mHandler = new Handler();
mRegistry.handleLifecycleEvent(Lifecycle.Event.ON_CREATE);
Application app = (Application) context.getApplicationContext();
app.registerActivityLifecycleCallbacks(new EmptyActivityLifecycleCallbacks() {
@RequiresApi(29)
@Override
public void onActivityPreCreated(@NonNull Activity activity,
@Nullable Bundle savedInstanceState) {
// log
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) {
// log
if (Build.VERSION.SDK_INT < 29) {
// 注意此处,为ReportFragment添加ActivityInitializationListener
ReportFragment.get(activity).setProcessListener(mInitializationListener);
}
}

@Override
public void onActivityPaused(Activity activity) {
// 注意此处
activityPaused();
}

@Override
public void onActivityStopped(Activity activity) {
// 注意此处
activityStopped();
}
});
}

我们发现这里为Application添加了生命周期监听,此监听分为两个部分:

  • 创建部分分别为 api29以下和API29及以上 注册了监听
  • 停止部分调用了内部方法activityPaused和activityStopped

由前文可知,生命周期变化是会通知回调,最终会通知ReportFragment,在前面介绍生命周期分发过程中ReportFragment中有一部分关于ActivityInitializationListener 我没有介绍:

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
public class ReportFragment extends android.app.Fragment {
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);
}
// others
}

上述ProcessLifecycleOwner为ReportFragment添加 ActivityInitializationListener,在生命周期变化是会通知ProcessLifecycleOwner中的ActivityInitializationListener对象:

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
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
ActivityInitializationListener mInitializationListener =
new ActivityInitializationListener() {
@Override
public void onCreate() {
}

@Override
public void onStart() {
activityStarted();
}

@Override
public void onResume() {
activityResumed();
}
};

void activityStarted() {
mStartedCounter++;
if (mStartedCounter == 1 && mStopSent) {
mRegistry.handleLifecycleEvent(Lifecycle.Event.ON_START);
mStopSent = false;
}
}

void activityResumed() {
mResumedCounter++;
if (mResumedCounter == 1) {
if (mPauseSent) {
mRegistry.handleLifecycleEvent(Lifecycle.Event.ON_RESUME);
mPauseSent = false;
} else {
mHandler.removeCallbacks(mDelayedPauseRunnable);
}
}
}

void activityPaused() {
mResumedCounter--;
if (mResumedCounter == 0) {
mHandler.postDelayed(mDelayedPauseRunnable, TIMEOUT_MS);
}
}

void activityStopped() {
mStartedCounter--;
dispatchStopIfNeeded();
}

void dispatchPauseIfNeeded() {
if (mResumedCounter == 0) {
mPauseSent = true;
mRegistry.handleLifecycleEvent(Lifecycle.Event.ON_PAUSE);
}
}

void dispatchStopIfNeeded() {
if (mStartedCounter == 0 && mPauseSent) {
mRegistry.handleLifecycleEvent(Lifecycle.Event.ON_STOP);
mStopSent = true;
}
}

由代码可知,在展示时调用 activityStarted 和 activityResumed 并作计数递增,在停止时调用 activityPaused 和 activityStopped 做计数递减,并判断计数是否为0, 为零则执行 LifecycleRegistry.handleLifecycleEvent 通知到我们注册的 LifecycleObserver, 其通知流程与Activity生命周期分发到LifecycleObserver一致。

至此,整个流程结束。