Lifecycle-aware Components 源码分析

注:本文所有代码基于 android.arch.lifecycle 1.0.0-alpha1
另外,为了避免混淆,Fragment、Activity 等组件自身的生命周期直用 “生命周期” 一词,而由 Lifecycle 框架提供的生命周期则称为 “lifecyle”

最近看到不少人讨论 Google 推的 Android Architecture Components,其中 Handling Lifecycles 一章展现了如何利用 android.arch.lifecycle 包提供的类来控制数据、监听器等的 lifecycle。同时,LiveDataViewModel 的 lifecycle 也依赖于 Lifecycle 框架,所以分析 Lifecycle 显然是有必要的。

Lifecycle 到底是通过怎样的方式来绑定 Android 组件的生命周期以及如何通知 LifecycleObserver 状态变化的呢?本文将会围绕这两个问题深入分析 Lifecycle 源码。

前置工作

由于完整的 Lifecycle 分为 common, core, extensions, runtime 四个包,并包含 ViewModelLiveData 部分内容。为了方便分析,利用 proguard(只添加 -dontobfuscate) 剔除所有不需要用到的类。

最终剩下的类:

android.arch.core.internal(core

  • SafeIterableMap

android.arch.lifecycle(runtime

  • EmptyActivityLifecycleCallbacks
  • LifecycleActivity
  • LifecycleDispatcher
  • LifecycleFragment
  • LifecycleRegistry
  • LifecycleRegistryOwner
  • LifecycleRuntimeTrojanProvider
  • LifecycleService
  • ProcessLifecycleOwner
  • ReportFragment
  • ServiceLifecycleDispatcher

android.arch.lifecycle(common

  • GenericLifecycleObserver
  • Lifecycle
  • LifecycleObserver
  • LifecycleOwner
  • Lifecycling
  • OnLifecycleEvent
  • ReflectiveGenericLifecycleObserver

Lifecycle 事件的生成过程

先看 Lifecycle 的 AndroidManifest.xml(可以在 build/outputs/logs/manifest-merger-*.txt 中找到对应的路径):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="android.arch.lifecycle"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="14"
android:targetSdkVersion="26" />
<application>
<provider
android:name="android.arch.lifecycle.LifecycleRuntimeTrojanProvider"
android:authorities="${applicationId}.lifecycle-trojan"
android:exported="false"
android:multiprocess="true" />
</application>
</manifest>

可以看到 Lifecycle框架会给应用添加一个 exported="false"LifecycleRuntimeTrojanProvider

LifecycleRuntimeTrojanProvider

1
2
3
4
5
6
7
8
9
10
11
12
13
14
/**
* Internal class to initialize Lifecycles.
* @hide
*/
public class LifecycleRuntimeTrojanProvider extends ContentProvider {
@Override
public boolean onCreate() {
LifecycleDispatcher.init(getContext());
ProcessLifecycleOwner.init(getContext());
return true;
}
...
}

javadoc 已经写得很明显,LifecycleRuntimeTrojanProvider 就是用于初始化 Lifecycle 框架的,其余 ContentProvider 应实现的方法返回的均为默认值(null 或 0),顺着代码先看 LifecycleDispatcher

LifecycleDispatcher

LifecycleDispatcher 的初始化代码比较简单:

1
2
3
4
5
6
7
8
9
private static AtomicBoolean sInitialized = new AtomicBoolean(false);
static void init(Context context) {
if (sInitialized.getAndSet(true)) {
return;
}
((Application) context.getApplicationContext())
.registerActivityLifecycleCallbacks(new DispatcherActivityCallback());
}

主要就是注册了一个 ActivityLifecycleCallbacks —— DispatcherActivityCallback

DispatcherActivityCallback

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
static class DispatcherActivityCallback extends EmptyActivityLifecycleCallbacks {
private final FragmentCallback mFragmentCallback;
DispatcherActivityCallback() {
mFragmentCallback = new FragmentCallback();
}
@Override
public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
if (activity instanceof FragmentActivity) {
((FragmentActivity) activity).getSupportFragmentManager()
.registerFragmentLifecycleCallbacks(mFragmentCallback, true);
}
// 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();
}
}
@Override
public void onActivityStopped(Activity activity) {
if (activity instanceof FragmentActivity) {
markState((FragmentActivity) activity, CREATED);
}
}
@Override
public void onActivitySaveInstanceState(Activity activity, Bundle outState) {
if (activity instanceof FragmentActivity) {
markState((FragmentActivity) activity, CREATED);
}
}
}

DispatcherActivityCallbackonActivityStoppedonActivitySaveInstanceState 方法会将 LifecycleRegistryOwner 的状态重置成 CREATED(为何是 CREATED 可以查看 Lifecycle 的状态图各状态的描述)。再看 onActivityCreated,当 activity 是 FragmentActivity 时,额外注册 FragmentLifecycleCallbacks —— FragmentCallback,紧接着将 ReportFragment 添加到 activity 中。考虑到并不是所有人都会使用 FragmentActivity,所以添加 ReportFragment 时使用的是原生的 FragmentManager。

ReportFragment

先来看一下 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
76
77
78
79
80
81
public class ReportFragment extends 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);
}
@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) {
if (getActivity() instanceof LifecycleRegistryOwner) {
((LifecycleRegistryOwner) getActivity()).getLifecycle().handleLifecycleEvent(event);
}
}
void setProcessListener(ActivityInitializationListener processListener) {
mProcessListener = processListener;
}
interface ActivityInitializationListener {
void onCreate();
void onStart();
void onResume();
}
}

这里可以看出 ReportFragment 在生命周期发生变化时会生成对应的 lifecycle 事件并通过 dispatch(event) 将事件发送到 LifecyclehandleLifecycleEvent(event) 方法中。此外还会在 onActivityCreated, onStart, onResume 时额外通知 ActivityInitializationListener(暂且记住,后面会用到)。可能会有读者有疑问,为什么要使用 ReportFragment 的生命周期而不直接使用 ActivityLifecycleCallbacks 的回调来处理 lifecycle 的变化?由于 ActivityLifecycleCallbacks 的回调比 Fragment 和 Activity 还要早,实际上未真正执行对应的生命周期方法。至于为什么用 Fragment 而不直接重写 Activity 的生命周期,显然用 Fragment 侵入性低。

FragmentCallback

再看回 FragmentCallback

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
static class FragmentCallback extends FragmentManager.FragmentLifecycleCallbacks {
@Override
public void onFragmentCreated(FragmentManager fm, Fragment f, Bundle savedInstanceState) {
dispatchIfLifecycleOwner(f, ON_CREATE);
if (!(f instanceof LifecycleRegistryOwner)) {
return;
}
if (f.getChildFragmentManager().findFragmentByTag(REPORT_FRAGMENT_TAG) == null) {
f.getChildFragmentManager().beginTransaction().add(new DestructionReportFragment(),
REPORT_FRAGMENT_TAG).commit();
}
}
@Override
public void onFragmentStarted(FragmentManager fm, Fragment f) {
dispatchIfLifecycleOwner(f, ON_START);
}
@Override
public void onFragmentResumed(FragmentManager fm, Fragment f) {
dispatchIfLifecycleOwner(f, ON_RESUME);
}
}
private static void dispatchIfLifecycleOwner(Fragment fragment, Lifecycle.Event event) {
if (fragment instanceof LifecycleRegistryOwner) {
((LifecycleRegistryOwner) fragment).getLifecycle().handleLifecycleEvent(event);
}
}

FragmentCallbackonFragmentCreated, onFragmentStarted, onFragmentResumed 分别生成了 ON_CREATE, ON_START, ON_RESUME 三个 lifecycle 事件。

DispatcherActivityCallback 类似,当 Fragment 为 Parent Fragment 且实现了 LifecycleRegistryOwner 接口时,FragmentCallback 会添加一个 Child Fragment —— DestructionReportFragment

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
public static class DestructionReportFragment extends Fragment {
@Override
public void onPause() {
super.onPause();
dispatch(ON_PAUSE);
}
@Override
public void onStop() {
super.onStop();
dispatch(ON_STOP);
}
@Override
public void onDestroy() {
super.onDestroy();
dispatch(ON_DESTROY);
}
protected void dispatch(Lifecycle.Event event) {
dispatchIfLifecycleOwner(getParentFragment(), event);
}
}

在这里我们可以看出,DestructionReportFragment 会在 onPause, onStop, onDestroy 中生成对应的 lifecycle 事件并转发到 Parent Fragment 中。

结合 FragmentCallbackDestructionReportFragment,我们可以知道 FragmentCallback 混合了 FragmentLifecycleCallbacks 及 Fragment 的生命周期来通知 LifecycleObserver lifecycle 发生变化。这样做是为了确保 ON_CREATE, ON_START, ON_RESUME 发生在相应的生命周期之后,ON_PAUSE, ON_STOP, ON_DESTROY 发生在相应的生命周期之前(不明白的可参考 Lifecycle)。

所以 FragmentCallback 主要是通知 Fragment(implements LifecycleRegistryOwner)lifecycle 发生变化,从而给 LifecycleObserver 分发 lifecycle 事件。

值得注意的是,由于 FragmentLifecycleCallbacks 只存在于 v4 包中,所以当 LifecycleRegistryOwner 是 android.app.Fragment 时,该 Fragment 相关生命周期发生变化也不会主动产生相关的 lifecycle 事件。也就是说,即使 LifecycleObserver 已经通过 getLifecycle().addObserver(this) 注册了监听,也不会接收到相应的 lifecycle 事件,因为没有对应的生产者。(Google 的 BUG,相关的 issue 可以看此链接。同时感谢 @QichaoChen 提供的信息)

ProcessLifecycleOwner

看完 LifecycleDispatcher,接着来了解一下 ProcessLifecycleOwner

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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
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() {
dispatchPauseIfNeeded();
dispatchStopIfNeeded();
}
};
private 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();
public static LifecycleOwner get() {
return sInstance;
}
static void init(Context context) {
sInstance.attach(context);
}
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();
}
private void dispatchPauseIfNeeded() {
if (mResumedCounter == 0) {
mPauseSent = true;
mRegistry.handleLifecycleEvent(Lifecycle.Event.ON_PAUSE);
}
}
private void dispatchStopIfNeeded() {
if (mStartedCounter == 0 && mPauseSent) {
mRegistry.handleLifecycleEvent(Lifecycle.Event.ON_STOP);
mStopSent = true;
}
}
private ProcessLifecycleOwner() {
}
void attach(Context context) {
mHandler = new Handler();
mRegistry.handleLifecycleEvent(Lifecycle.Event.ON_CREATE);
Application app = (Application) context.getApplicationContext();
app.registerActivityLifecycleCallbacks(new EmptyActivityLifecycleCallbacks() {
@Override
public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
LifecycleDispatcher.get(activity).setProcessListener(mInitializationListener);
}
@Override
public void onActivityPaused(Activity activity) {
activityPaused();
}
@Override
public void onActivityStopped(Activity activity) {
activityStopped();
}
});
}
@Override
public Lifecycle getLifecycle() {
return mRegistry;
}
}

比起 LifecycleDispatcherProcessLifecycleOwner 的代码要简单得多。ProcessLifecycleOwner 的作用就是根据当前进程中 Activity 的状态变化统计 Activity 的数量从而得出当前进程的变化并通知 LifecycleObserver lifecycle 发生变化。

而为了达到这一目的,ProcessLifecycleOwner 的做法是为 LifecycleDispatcher 注册 ActivityInitializationListener 以确保 Activity 进入了 onStartonResume 生命周期(还记得前面 ReportFragment 提到的这部分内容?),并配合 ActivityLifecycleCallbacks 的 onActivityPaused, onActivityStopped 确保 lifecycle 事件发生在 Activity 的 onPause, onStop 之前。

需注意的是,由于 ProcessLifecycleOwner 没有 ON_DESTROY,当接收到 ON_STOP 时 lifecycle 已经结束。另外,ProcessLifecycleOwner 的统计不包含 Service,换句话说,即使接收到 ON_STOP 事件,并不意味着当前进程结束,只表示当前进程无存活的 Activity。

LifecycleService

了解完 Lifecycle 框架中 Activity、Fragment 相关的 lifecycle 事件是如何生成的,接下来就看一下 Service 又是怎么做的。

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
public class LifecycleService extends Service implements LifecycleOwner {
private final ServiceLifecycleDispatcher mDispatcher = new ServiceLifecycleDispatcher(this);
@CallSuper
@Override
public void onCreate() {
mDispatcher.onServicePreSuperOnCreate();
super.onCreate();
}
@CallSuper
@Nullable
@Override
public IBinder onBind(Intent intent) {
mDispatcher.onServicePreSuperOnBind();
return null;
}
@SuppressWarnings("deprecation")
@CallSuper
@Override
public void onStart(Intent intent, int startId) {
mDispatcher.onServicePreSuperOnStart();
super.onStart(intent, startId);
}
@CallSuper
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
return super.onStartCommand(intent, flags, startId);
}
@CallSuper
@Override
public void onDestroy() {
mDispatcher.onServicePreSuperOnDestroy();
super.onDestroy();
}
@Override
public Lifecycle getLifecycle() {
return mDispatcher.getLifecycle();
}
}
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
public class ServiceLifecycleDispatcher {
private final LifecycleRegistry mRegistry;
private final Handler mHandler;
private DispatchRunnable mLastDispatchRunnable;
public ServiceLifecycleDispatcher(@NonNull LifecycleOwner provider) {
mRegistry = new LifecycleRegistry(provider);
mHandler = new Handler();
}
private void postDispatchRunnable(Lifecycle.Event event) {
if (mLastDispatchRunnable != null) {
mLastDispatchRunnable.run();
}
mLastDispatchRunnable = new DispatchRunnable(mRegistry, event);
mHandler.postAtFrontOfQueue(mLastDispatchRunnable);
}
public void onServicePreSuperOnCreate() {
postDispatchRunnable(Lifecycle.Event.ON_CREATE);
}
public void onServicePreSuperOnBind() {
postDispatchRunnable(Lifecycle.Event.ON_START);
}
public void onServicePreSuperOnStart() {
postDispatchRunnable(Lifecycle.Event.ON_START);
}
public void onServicePreSuperOnDestroy() {
postDispatchRunnable(Lifecycle.Event.ON_STOP);
postDispatchRunnable(Lifecycle.Event.ON_DESTROY);
}
public Lifecycle getLifecycle() {
return mRegistry;
}
static class DispatchRunnable implements Runnable {
private final LifecycleRegistry mRegistry;
final Lifecycle.Event mEvent;
private boolean mWasExecuted = false;
DispatchRunnable(@NonNull LifecycleRegistry registry, Lifecycle.Event event) {
mRegistry = registry;
mEvent = event;
}
@Override
public void run() {
if (!mWasExecuted) {
mRegistry.handleLifecycleEvent(mEvent);
mWasExecuted = true;
}
}
}
}

ServiceLifecycleDispatcher 用于协助 LifecycleService 分发 lifecycle 事件并确保每次发生变化时回调执行于 Handler 中。同时我们可以看到 LifecycleService 只会产生 ON_CREATE, ON_START, ON_STOP, ON_DESTROY 四种事件。

需注意的是继承 LifecycleService 时如需重写 onStartonStartCommand 方法,必须调用 super.onStartsuper.onStartCommand 以确保 ON_START 事件能够被触发。

小结

至此,我们了解到 Lifecycle 框架是如何将 lifecycle 事件与 Android 组件的生命周期绑定的:

  • LifecycleDispatcher,通过 ActivityLifecycleCallbacks、FragmentLifecycleCallbacks 及 Fragment 获知 Activity、Fragment 的生命周期变化并产生相应的 lifecycle 事件;
  • ProcessLifecycleOwner,通过 ActivityLifecycleCallbacks 与 LifecycleDispatcher 配合监听当前进程中 Activities 的生命周期变化并在必要时产生相应的 lifecycle 事件;
  • LifecycleService,通过重写 Service 的生命周期方法并在相应方法内产生相应的 lifecycle 事件。

Lifecycle 事件的分发过程

在之前的分析中我们就留意到 lifecycle 事件生成后均会通过 LifecycleOwner 或 LifecycleRegistryOwner(extends LifecycleOwner)的 getLifecycle() 获取 Lifecycle 类或 LifecycleRegistry(extends Lifecycle),再通过它的 handleLifecycleEvent(event) 进行事件的分发。

那么各个 getLifecycle() 是怎样的呢?我们来看一下:

1
2
3
4
5
6
7
8
9
public class LifecycleActivity extends FragmentActivity implements LifecycleRegistryOwner {
private final LifecycleRegistry mRegistry = new LifecycleRegistry(this);
@Override
public LifecycleRegistry getLifecycle() {
return mRegistry;
}
}
1
2
3
4
5
6
7
8
public class LifecycleFragment extends Fragment implements LifecycleRegistryOwner {
LifecycleRegistry mLifecycleRegistry = new LifecycleRegistry(this);
@Override
public LifecycleRegistry getLifecycle() {
return mLifecycleRegistry;
}
}
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
public class LifecycleService extends Service implements LifecycleOwner {
private final ServiceLifecycleDispatcher mDispatcher = new ServiceLifecycleDispatcher(this);
...
@Override
public Lifecycle getLifecycle() {
return mDispatcher.getLifecycle();
}
}
public class ServiceLifecycleDispatcher {
private final LifecycleRegistry mRegistry;
public ServiceLifecycleDispatcher(@NonNull LifecycleOwner provider) {
mRegistry = new LifecycleRegistry(provider);
...
}
public Lifecycle getLifecycle() {
return mRegistry;
}
...
}

从上面的代码我们知道,LifecycleActivityLifecycleFragmentLifecycleServicegetLifecycle() 返回的均为 LifecycleRegistryProcessLifecycleOwner 也一样)。

LifecycleRegistry 的 addObserver 流程

因为接收 lifecycle 事件都需先通过 LifecycleaddObserver 注册 LifecycleObserver,所以我们先了解一下 LifecycleRegistryaddObserver 的内部逻辑:

1
2
3
4
5
6
7
8
9
private SafeIterableMap<LifecycleObserver, ObserverWithState> mObserverSet =
new SafeIterableMap<>();
@Override
public void addObserver(LifecycleObserver observer) {
ObserverWithState observerWithState = new ObserverWithState(observer);
mObserverSet.putIfAbsent(observer, observerWithState);
observerWithState.sync();
}
1
2
3
4
5
6
7
8
9
10
class ObserverWithState {
private State mObserverCurrentState = INITIALIZED;
private GenericLifecycleObserver mCallback;
ObserverWithState(LifecycleObserver observer) {
mCallback = Lifecycling.getCallback(observer);
}
...
}

其中 SafeIterableMap 是一个可在遍历过程中进行修改的 Iterable<Map.Entry<K, V>>

在调用 LifecycleRegistryaddObserver 方法时,LifecycleObserver 被传至 ObserverWithState 并通过 Lifecycling.getCallback(observer) 生成 GenericLifecycleObserver

Lifecycling

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
@NonNull
static GenericLifecycleObserver getCallback(Object object) {
if (object instanceof GenericLifecycleObserver) {
return (GenericLifecycleObserver) object;
}
... // try
final Class<?> klass = object.getClass();
Constructor<? extends GenericLifecycleObserver> cachedConstructor;
... // 缓存部分
cachedConstructor = getGeneratedAdapterConstructor(klass);
if (cachedConstructor != null) {
sCallbackCache.put(klass, cachedConstructor);
if (!cachedConstructor.isAccessible()) {
cachedConstructor.setAccessible(true);
}
return cachedConstructor.newInstance(object);
} else {
sCallbackCache.put(klass, sREFLECTIVE);
}
return new ReflectiveGenericLifecycleObserver(object);
... // catch
}

当调用 getCallback 时,Lifecycling 会根据传入的 Object(LifecycleObserver)调用 getGeneratedAdapterConstructor

LifecycleAdapter 的实例化

接着看 getGeneratedAdapterConstructor 的源码:

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
@Nullable
private static Constructor<? extends GenericLifecycleObserver> getGeneratedAdapterConstructor(
Class<?> klass) {
final String fullPackage = klass.getPackage().getName();
String name = klass.getCanonicalName();
// anonymous class bug:35073837
if (name == null) {
return null;
}
final String adapterName = getAdapterName(fullPackage.isEmpty() ? name :
name.substring(fullPackage.length() + 1));
try {
@SuppressWarnings("unchecked")
final Class<? extends GenericLifecycleObserver> aClass =
(Class<? extends GenericLifecycleObserver>) Class.forName(
fullPackage.isEmpty() ? adapterName : fullPackage + "." + adapterName);
return aClass.getDeclaredConstructor(klass);
} catch (ClassNotFoundException e) {
final Class<?> superclass = klass.getSuperclass();
if (superclass != null) {
// 找不到 LifecycleAdapter 时获取父类的 LifecycleAdapter
return getGeneratedAdapterConstructor(superclass);
}
} catch (NoSuchMethodException e) {
// this should not happen
throw new RuntimeException(e);
}
return null;
}
static String getAdapterName(String className) {
return className.replace(".", "_") + "_LifecycleAdapter";
}

不难看出,getGeneratedAdapterConstructor 主要是获取 annotationProcessor 生成的 xxx_LifecycleAdapter(关于 LifecycleAdapter 后面补充说明)的构造函数,并实例化返回到 getCallback 中。需注意的是,如果找不到 LifecycleAdapter 且 object(LifecycleObserver) 存在父类时会试图获取父类的 LifecycleAdapter(估计是为了应对混淆时只混淆了子类的情况)。

ReflectiveGenericLifecycleObserver 的实例化

当获取 LifecycleAdapter 失败后,Lifecycling 会直接实例化 ReflectiveGenericLifecycleObserver 作为替代(估计也是为了应对混淆)。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
class ReflectiveGenericLifecycleObserver implements GenericLifecycleObserver {
private final Object mWrapped;
private final CallbackInfo mInfo;
@SuppressWarnings("WeakerAccess")
static final Map<Class, CallbackInfo> sInfoCache = new HashMap<>();
ReflectiveGenericLifecycleObserver(Object wrapped) {
mWrapped = wrapped;
mInfo = getInfo(mWrapped.getClass());
}
...
private static CallbackInfo getInfo(Class klass) {
CallbackInfo existing = sInfoCache.get(klass);
if (existing != null) {
return existing;
}
existing = createInfo(klass);
return existing;
}
...
}

ReflectiveGenericLifecycleObserver 在实例化时会获取 Object(LifecycleObserver)的 class 并作为参数调用 createInfo 方法。

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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
private static CallbackInfo createInfo(Class klass) {
Method[] methods = klass.getDeclaredMethods();
List<MethodReference> methodReferences = null;
Set<Event> allEvents = new HashSet<>();
for (Method method : methods) {
OnLifecycleEvent annotation = method.getAnnotation(OnLifecycleEvent.class);
if (annotation == null) {
continue;
}
Class<?>[] params = method.getParameterTypes();
int callType = CALL_TYPE_NO_ARG;
if (params.length > 0) {
callType = CALL_TYPE_PROVIDER;
// 有参第一个参数必须为 LifecycleOwner
if (!params[0].isAssignableFrom(LifecycleOwner.class)) {
throw new IllegalArgumentException(
"invalid parameter type. Must be one and instanceof LifecycleOwner");
}
}
if (params.length > 1) {
callType = CALL_TYPE_PROVIDER_WITH_EVENT;
// 有两个参数时第二个参数必须为 Event
if (!params[1].isAssignableFrom(Event.class)) {
throw new IllegalArgumentException(
"invalid parameter type. second arg must be an event");
}
}
if (params.length > 2) {
// 最多只能有两个参数
throw new IllegalArgumentException("cannot have more than 2 params");
}
if (methodReferences == null) {
methodReferences = new ArrayList<>();
}
// 获取应该执行回调的事件集
Set<Event> events = expandOnAnyEvents(annotation.value());
methodReferences.add(new MethodReference(events, callType, method));
allEvents.addAll(events);
}
CallbackInfo info = new CallbackInfo(allEvents, methodReferences);
sInfoCache.put(klass, info);
Class superclass = klass.getSuperclass();
if (superclass != null) {
// 获取父类中带 OnLifecycleEvent 注解的方法集及事件集等
info.mSuper = getInfo(superclass);
}
Class[] interfaces = klass.getInterfaces();
// 获取接口中带 OnLifecycleEvent 注解的方法集及事件集等
for (Class intrfc : interfaces) {
CallbackInfo interfaceInfo = getInfo(intrfc);
if (!interfaceInfo.mEvents.isEmpty()) {
if (info.mInterfaces == null) {
info.mInterfaces = new ArrayList<>();
}
info.mInterfaces.add(interfaceInfo);
}
}
return info;
}
@SuppressWarnings("WeakerAccess")
static class CallbackInfo {
final Set<Event> mEvents;
@Nullable
List<MethodReference> mMethodReferences;
@Nullable
List<CallbackInfo> mInterfaces;
@Nullable
CallbackInfo mSuper;
CallbackInfo(Set<Event> events, @Nullable List<MethodReference> methodReferences) {
mEvents = events;
mMethodReferences = methodReferences;
}
}
@SuppressWarnings("WeakerAccess")
static class MethodReference {
final Set<Event> mEvents;
final int mCallType;
final Method mMethod;
MethodReference(Set<Event> events, int callType, Method method) {
mEvents = events;
mCallType = callType;
mMethod = method;
mMethod.setAccessible(true);
}
}
private static Set<Event> expandOnAnyEvents(Event[] events) {
boolean hasOnAllEvents = false;
for (Event e: events) {
if (e == Event.ON_ANY) {
hasOnAllEvents = true;
break;
}
}
if (!hasOnAllEvents) {
HashSet<Event> set = new HashSet<>();
Collections.addAll(set, events);
return set;
} else {
return ALL_EVENTS;
}
}
private static final Set<Event> ALL_EVENTS = new HashSet<Event>() {
{
add(Event.ON_CREATE);
add(Event.ON_START);
add(Event.ON_RESUME);
add(Event.ON_PAUSE);
add(Event.ON_STOP);
add(Event.ON_DESTROY);
}
};
private static final int CALL_TYPE_NO_ARG = 0;
private static final int CALL_TYPE_PROVIDER = 1;
private static final int CALL_TYPE_PROVIDER_WITH_EVENT = 2;

从上面的代码可以了解到,createInfo 主要是获取所有带 OnLifecycleEvent 注解的方法,在判断这些方法的合法性后,根据对应方法的参数个数、事件类型及方法名实例化 MethodReference 并添加到 List<MethodReference> 中,同时亦会将 Object(LifecycleObserver) 涉及的所有事件类型保存到 Set<Event> 中。当遍历完 Object(LifecycleObserver) 定义的所有方法后,会根据 List<MethodReference>Set<Event> 实例化 CallbackInfo 并缓存至 sInfoCache。最后对 Object(LifecycleObserver) 的父类和接口执行同样的操作(即以它们作为参数传入 createInfo),并将返回的 CallbackInfo 分别赋值给 info.mSuperinfo.mInterfaces 供后面使用。

ObserverWithState 的 sync 流程

GenericLifecycleObserver 的实例化完成后,addObserver 会调用 ObserverWithStatesync 方法:

1
2
3
4
5
6
7
8
9
10
11
12
13
observerWithState.sync();
void sync() {
if (mState == DESTROYED && mObserverCurrentState == INITIALIZED) {
mObserverCurrentState = DESTROYED;
}
while (mObserverCurrentState != mState) {
Event event = mObserverCurrentState.isAtLeast(mState)
? downEvent(mObserverCurrentState) : upEvent(mObserverCurrentState);
mObserverCurrentState = getStateAfter(event);
mCallback.onStateChanged(mLifecycleOwner, event);
}
}

其中 mState 表示的是 LifecycleRegistry 当前所处的状态。

如果当前 LifecycleRegistry 处于 DESTROYEDObserverWithState 处于 INITIALIZED 时,ObserverWithState 会直接进入 DESTROYED,并且此时 LifecycleObserver 不会收到任何回调。

ObserverWithStateLifecycleRegistry 的状态不相同时,ObserverWithState 会通过 mObserverCurrentState.isAtLeast(mState) 比较自身状态是高于或低于 LifecycleRegistry 的状态。状态的高低顺序(升序)如下:

1
2
3
4
5
6
7
8
9
10
public enum State {
DESTROYED,
INITIALIZED,
CREATED,
STARTED,
RESUMED;
public boolean isAtLeast(State state) {
return compareTo(state) >= 0;
}
}

ObserverWithState 的状态高于或低于 LifecycleRegistry 时,会分别调用 downEventupEvent 决定 LifecycleObserver 的下一个 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
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);
}
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);
}

紧接着 ObserverWithState 会将获得的事件类型传入 getStateAfter 中获取新的状态:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
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);
}

如果修改完状态后 ObserverWithStateLifecycleRegistry 的状态依然不相同,上述过程会一直重复执行直到相同为止。例如,当 LifecycleRegistry 处于 RESUMEDObserverWithState 处于 INITIALIZED 时,ObserverWithState 的状态会按照 INITIALIZED -> CREATED -> STARTED -> RESUMED 这样的顺序变迁。

下面再来了解下每次状态变迁之后调用的 OnStateChanged 方法内部做了些什么。

从前面 GenericLifecycleObserver 的生成过程中我们可以知道,这里的分析也需要分为两种情况分析:

  • LifecycleAdapter
  • ReflectiveGenericLifecycleObserver
LifecycleAdapter

由于没有找到 LifecycleProcessor 的源码,这里我就写了个 DataObserver 来让各位稍微了解一下 LifecycleAdapter(可在 build/generated/source/apt 中找到):

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 DataObserver implements LifecycleObserver {
@OnLifecycleEvent(Lifecycle.Event.ON_ANY)
public void onAny() {
}
@OnLifecycleEvent(Lifecycle.Event.ON_CREATE)
public void onCreate() {
}
@OnLifecycleEvent(Lifecycle.Event.ON_START)
public void onStart() {
}
@OnLifecycleEvent(Lifecycle.Event.ON_RESUME)
public void onResume() {
}
@OnLifecycleEvent(Lifecycle.Event.ON_PAUSE)
public void onPause() {
}
@OnLifecycleEvent(Lifecycle.Event.ON_STOP)
public void onStop() {
}
@OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
public void onDestroy() {
}
}
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
public class DataObserver_LifecycleAdapter implements GenericLifecycleObserver {
final DataObserver mReceiver;
DataObserver_LifecycleAdapter(DataObserver receiver) {
this.mReceiver = receiver;
}
@Override
public void onStateChanged(LifecycleOwner owner, Lifecycle.Event event) {
mReceiver.onAny();
if (event == Lifecycle.Event.ON_CREATE) {
mReceiver.onCreate();
}
if (event == Lifecycle.Event.ON_START) {
mReceiver.onStart();
}
if (event == Lifecycle.Event.ON_RESUME) {
mReceiver.onResume();
}
if (event == Lifecycle.Event.ON_PAUSE) {
mReceiver.onPause();
}
if (event == Lifecycle.Event.ON_STOP) {
mReceiver.onStop();
}
if (event == Lifecycle.Event.ON_DESTROY) {
mReceiver.onDestroy();
}
}
public Object getReceiver() {
return mReceiver;
}
}

从 DataObserver_LifecycleAdapter 中可以大概猜测到,LifecycleProcessor 生成的 LifecycleAdapter 会根据 LifecycleObserver 中带 OnLifecycleEvent 注解的方法生成 onStateChanged,而且 onStateChanged 会根据不同的事件分别执行 LifecycleObserver 中对应的方法。

ReflectiveGenericLifecycleObserver

当 lifecycle 发生变化调用 onStateChanged 时:

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
@Override
public void onStateChanged(LifecycleOwner source, Event event) {
invokeCallbacks(mInfo, source, event);
}
@SuppressWarnings("ConstantConditions")
private void invokeCallbacks(CallbackInfo info, LifecycleOwner source, Event event) {
// 当前 ReflectiveGenericLifecycleObserver 有无该事件的相关注解
if (info.mEvents.contains(event)) {
for (int i = info.mMethodReferences.size() - 1; i >= 0; i--) {
MethodReference reference = info.mMethodReferences.get(i);
invokeCallback(reference, source, event);
}
}
// TODO prevent duplicate calls into the same method. Preferably while parsing
if (info.mSuper != null) {
// 交由此前传入的 LifecycleObserver 的父类处理
invokeCallbacks(info.mSuper, source, event);
}
if (info.mInterfaces != null) {
final int size = info.mInterfaces.size();
for (int i = 0; i < size; i++) {
// 交由此前传入的 LifecycleObserver 的接口处理
invokeCallbacks(info.mInterfaces.get(i), source, event);
}
}
}
private void invokeCallback(MethodReference reference, LifecycleOwner source, Event event) {
// MethodReference 是否包含该事件
if (reference.mEvents.contains(event)) {
try {
switch (reference.mCallType) {
case CALL_TYPE_NO_ARG:
reference.mMethod.invoke(mWrapped);
break;
case CALL_TYPE_PROVIDER:
reference.mMethod.invoke(mWrapped, source);
break;
case CALL_TYPE_PROVIDER_WITH_EVENT:
reference.mMethod.invoke(mWrapped, source, event);
break;
}
} catch (InvocationTargetException e) {
throw new RuntimeException("Failed to call observer method", e.getCause());
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
}
}
}

ReflectiveGenericLifecycleObserver 会判断接收到的事件是否存在于 createInfo 生成的 mInfo 中的事件集之中。当存在时,会遍历此前缓存的方法列表并由 MethodReference 判断是否处理该事件。当需要处理时,会根据此前得到的 callType 决定传递哪些参数。同样的,在处理完 class(LifecycleObserver) 自身定义的方法后,会将事件分发给父类和接口的 MethodReference 处理。

小结

所以 sync 方法的用途是使 LifecycleObserver 的状态与 LifecycleRegistry 的状态同步并通知 LifecycleObserver 状态已经发生变化。

至此,addObserver 完成了自身的工作。

handleLifecycleEvent 流程

ServiceLifecycleDispatcher, LifecycleDispatcher 等的源码我们可以看出所有 lifecycle 事件都是通过 LifecycleRegistryhandleLifecycleEvent 来处理:

1
2
3
4
5
6
7
8
9
10
public void handleLifecycleEvent(Lifecycle.Event event) {
if (mLastEvent == event) {
return;
}
mLastEvent = event;
mState = getStateAfter(event);
for (Map.Entry<LifecycleObserver, ObserverWithState> entry : mObserverSet) {
entry.getValue().sync();
}
}

有了前面的经验,我们就能很容易地知道当 lifecycle 发生变化时,handleLifecycleEvent
会通过 getStateAfter 获取当前应处的状态并修改 mState 值,紧接着遍历所有 ObserverWithState 并调用他们的 sync 方法来同步且通知 LifecycleObserver 状态发生变化。

小结

至此,我们了解到当 LifecycleRegistryaddObserverhandleLifecycleEvent 被调用时,新的 lifecycle 事件会被传到 LifecycleAdapterReflectiveGenericLifecycleObserveronStateChanged 中从而通知 LifecycleObserver lifecycle 发生变化。

最后

结合来看,lifecycle 事件可由 LifecycleDispatcher(ActivityLifecycleCallbacks, FragmentLifecycleCallbacks, Fragment), ProcessLifecycleOwner, LifecycleService 产生,并通过 LifecycleRegistry, LifecycleAdapter/ReflectiveGenericLifecycleObserver 传递给 LifecycleObserver。

至此,Lifecycle-aware Components 的基础框架分析完毕。

稍微再说几句

  • 个人认为该框架最有趣的地方在于使用 ReportFragment 监听 Activity 的生命周期;
  • Lifecycle 确实能帮助我们分拆 onCreate, onStart 等生命周期方法内所做的初始化、销毁操作,避免过多的代码堆在生命周期方法之中。只不过与 MVP 一样,会增加不少类,很小的项目也没什么必要使用;
  • 整个框架的代码比较干净利落,反正看起来压力不大,能学到的东西也不少。