0%

Lifecycle 源码分析

Lifecycle 源码解析

SafeIterableMap - 本质上是一个双链表伪装成的 Map,支持在遍历时候的修改(删除)操作

FastSafeIterableMap - 继承自 SafeIterableMap ,使用 HashMap 存取数据,速度更快,但同时占用内存也更大

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
38
39
40
41
42
43
enum Event {
// LifecycleOwner 的 onCreate 事件
ON_CREATE,
// LifecycleOwner 的 onStart 事件
ON_START,
// LifecycleOwner 的 onResume 事件
ON_RESUME,
// LifecycleOwner 的 onPause 事件
ON_PAUSE,
// LifecycleOwner 的 onStop 事件
ON_STOP,
// LifecycleOwner 的 onDestroy 事件
ON_DESTROY,
// ANY事件 能匹配以上所有事件
ON_ANY
}
```

```java
// Lifecycle 对象跟踪的组件(即 LifecycleOwner )当前的状态
enum State {
// LifecycleOwner 的 DESTROYED 状态,到达这个事件后,当前生命周期不会再发送其他事件。
// 对于 Activity 来说,Activity#onDestroy() 调用之后,就是 DESTROYED 状态
DESTROYED,
// LifecycleOwner 的初始状态。对于 Activity 来说,在 Activity 构造之后,在 Activity#onCreate() 之前的状态就是 INITIALIZED
INITIALIZED,
// LifecycleOwner CREATED 状态,对于 Activity 来说,在以下两种情况下会到达此状态:
// 1. 在 Activity#onCreate() 调用之后
// 2. 在 Activity#onStop() 调用之前
CRETED,
// LifecycleOwner STARTED 状态。对于 Activity 来说,在以下两种情况下回到达此状态:
// 1. 在 Activity#onStart() 调用之后
// 2. 在 Activity#onPause() 调用之前
STARTED,
// LifecycleOwner RESUME 状态。对于 Activity 来说,在 Activity#onResume() 调用之后就是 RESUMED 状态
RESUMED;

// 判断当前状态是否至少是指定状态
// RESUMED > STARTED > CREATED > INITIALIZED > DESTROYED
public boolean isAtLeast(@NonNull State state) {
return compare(state) >= 0;
}
}

Event 是一种事件,是一种过程,好比是一条线段,State 是一个状态,好比是一个点。线段两端是点,两点之间是线段。
所以对于 Activity 来说,其生命周期状态和事件关系如下图:

Activity生命周期状态与事件关系图

Lifecycle 抽象类:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
// 生命周期对象
// 事件 Event#ON_CREATE, Event#ON_START, Event#ON_RESUME 会在 LifecycleOwner 对应的方法返回之后发送
// 事件 Event#ON_PAUSE, Event#ON_STOP, Event#ON_DESTROY 会在 LifecycleOwner 调用之前被发送
// 比如: Event#ON_START 会在 Activity#onStart() 方法返回的时候发送; Event#ON_STOP 会在 Activity#onStop() 方法调用前发送
// 这样就保证了,观察者在观察的事件周期一定在 LifecycleOwner 生命周期内
abstract class Lifecycle {

// 将指定 LifecycleObserver 添加到观察者列表中去
// 当 LifecyclerOwner 发生变化的时候,会通知 LifecycleObserver
// 注意: 参数 LifecycleObserver 的状态会带到当前 LifecycleOwner 的状态
// 举个栗子:如果 LifecyleOwner 状态是 State#STARTED,当添加 LifecycleObserver
// 之后,会接收到事件: Event#ON_CREATE 和 EVENT#ON_START
public abstract void addObserver(LifecycleObserver observer);

// 将指定 LifecycleObserver 从观察者列表中移除
public abstract void removeObserver(LifecycleObserver observer);

// 获取当前生命周期状态
public abstract State getCurrentState();
}

LifecycleOwner 接口代表拥有生命周期的组件,例如 androidx.fragment.app.FragmentActivity,androidx.fragment.app.Fragment 都实现了该接口。当然也可以自己定义拥有生命周期的组件来作为 LifecyleOwner。

1
2
3
interface LifecycleOwner {
Lifecycle getLifecycle();
}

Lifecycle 是一个抽象类,其方法诸如 addObserver 等定义了方法规范,其实际实现类是 LifecycleRegistry。 该类可以处理多个观察者。

添加 Observer:

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
class LifecycleRegistry extends Lifecycle {

// FastSafeIterableMap - 支持在遍历过程中增删元素的双向链表
// 这个 mObserverMap 元素中,恒成立的是:如果 addtion_order(observer1) < addtion_order(observer2)
// 则 state(observer1) >= state(observer2)
// 即如果把所有 observer 组成的队列的 State 看成是一个数列,那么这个数列是非递增数列
private FastSafeIterableMap<LifecycleObserver, ObserverWithState> mObserverMap =
new FastSafeIterableMap<>();

@Override
public void addObserver(@NonNull LifecycleObserver observer) {
State initialState = mState == DESTROYED ? DESTROYED : INITIALIZED;
// 1. 将传入的 LifecyleObserver 对象包装成 ObserverWithState 对象
ObserverWithState statefulObserver = new ObserverWithState(observer, initialState);
// 2. 如果当前 observer 没有被添加,则将其添加到队列中;如果已添加则 return
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++;
// 3. 将参数 LifecycleObserver 的状态带到当前 LifecycleOwner 的状态
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.
// 4. 同步整个观察者队列中的状态
sync();
}
mAddingObserverCounter--;
}
}

注释1,ObserverWithState 是 LifecycleRegistry 的静态内部类

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
static class ObserverWithState {
State mState;
LifecycleEventObserver mLifecycleObserver;

ObserverWithState(LifecycleObserver observer, State initialState) {
// 5. 通过 Lifecycling#lifecycleEventObserver 方法将 LifecycleObserver 转换成 LifecycleEventObserver
mLifecycleObserver = Lifecycling.lifecycleEventObserver(observer);
mState = initialState;
}
}

// LifecyeleEventObserver 继承自 LifecycleObserver,能接收任何生命周期的变化。
public interface LifecyeleEventObserver extends LifecycleObserver {
void onStateChanged(LifecycleOwner source, Lifecycle.Event event);
}

注释5:Lifecycling#lifecycleEventObserver 方法

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
static LifecycleEventObserver lifecycleEventObserver(Object object) {
boolean isLifecycleEventObserver = object instanceof LifecycleEventObserver;
boolean isFullLifecycleObserver = object instanceof FullLifecycleObserver;

// 如果参数 object 是 LifecycleEventObserver 也是 FullLifecycleObserver,则返回 FullLifecycleObserverAdapter
if (isLifecycleEventObserver && isFullLifecycleObserver) {
return new FullLifecycleObserverAdapter((FullLifecycleObserver) object,
(LifecycleEventObserver) object);
}

// 如果 object 是 FullLifecycleObserver, 则返回 FullLifecycleObserverAdapter
if (isFullLifecycleObserver) {
return new FullLifecycleObserverAdapter((FullLifecycleObserver) object, null);
}

// 如果 object 是 LifecycleEventObserver,则返回 LifecycleEventObserver
if (isLifecycleEventObserver) {
return (LifecycleEventObserver) object;
}

final Class<?> klass = object.getClass();
// 判断 Observer 构造器类型,有两个返回值 GENERATED_CALLBACK(注解生成器类型) 和 REFLECTIVE_CALLBACK (反射类型)
int type = getObserverConstructorType(klass);
if (type == GENERATED_CALLBACK) {
List<Constructor<? extends GeneratedAdapter>> constructors =
sClassToAdapters.get(klass);
if (constructors.size() == 1) {
GeneratedAdapter generatedAdapter = createGeneratedAdapter(
constructors.get(0), object);
return new SingleGeneratedAdapterObserver(generatedAdapter);
}
GeneratedAdapter[] adapters = new GeneratedAdapter[constructors.size()];
for (int i = 0; i < constructors.size(); i++) {
adapters[i] = createGeneratedAdapter(constructors.get(i), object);
}
return new CompositeGeneratedAdaptersObserver(adapters);
}
// 基于反射调用的 LifecycleEventObserver
return new ReflectiveGenericLifecycleObserver(object);
}

发送 Event 事件:
继承关系:
AppCompatActivity -> FragmentActivity -> androidx.fragment.app.ComponentActivity

androidx.fragment.app.ComponentActivity#onCreate()

1
2
3
4
5
6
7
8
9
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mSavedStateRegistryController.performRestore(savedInstanceState);
// 6. 在必要情况下,注入一个 ReportFragment
ReportFragment.injectIfNeededIn(this);
if (mContentLayoutId != 0) {
setContentView(mContentLayoutId);
}
}

ReportFragment#injectIfNeededIn(this)

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
public class ReportFragment extends android.app.Fragment {
public static void injectIfNeededIn(Activity activity) {
if (Build.VERSION.SDK_INT >= 29) {
// API 29+,即 Android 10 及以上,通过 activity 注册 ActivityLifecycleCallbacks 来实现对 Activity 生命周期的监听
activity.registerActivityLifecycleCallbacks(
new LifecycleCallbacks());
}

// 在当前 Activity 中生成一个空的 ReportFragment, 通过 ReportFragment 的生命周期事件来对 Lifecycle.Event 事件进行分发
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();
}
}

// API 29+
static class LifecycleCallbacks implements Application.ActivityLifecycleCallbacks {

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

//... 其他方法实现省略
}

static void dispatch(@NonNull Activity activity, @NonNull Lifecycle.Event event) {
// 兼容之前 android.support.v7.app.AppCompatActivity
if (activity instanceof LifecycleRegistryOwner) {
((LifecycleRegistryOwner) activity).getLifecycle().handleLifecycleEvent(event);
return;
}

if (activity instanceof LifecycleOwner) {
Lifecycle lifecycle = ((LifecycleOwner) activity).getLifecycle();
if (lifecycle instanceof LifecycleRegistry) {
// 7. 调用 LifecycleRegistry#handleLifecycleEvent() 对 Lifecycle.Event 事件进行分发
((LifecycleRegistry) lifecycle).handleLifecycleEvent(event);
}
}
}

@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
dispatchCreate(mProcessListener);
dispatch(Lifecycle.Event.ON_CREATE);
}

private void dispatch(@NonNull Lifecycle.Event event) {
if (Build.VERSION.SDK_INT < 29) {
// API 29+ 已经通过 registerActivityLifecycleCallbacks 的方式实现了对 Activity 生命周期的监听
dispatch(getActivity(), event);
}
}
}

LifecycleRegistry#handleLifecycleEvent() 对 Lifecyle.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
public void handleLifecycleEvent(@NonNull Lifecycle.Event event) {
State next = getStateAfter(event);
// 将当前 LifecycleOwner 中的 Observer 列表中的状态移至指定状态
moveToState(next);
}

// 事件(Event) 的触发,就会引起 状态(State) 的变化
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 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;
}

LifecycleRegistry#sync() 同步 Observer 队列的状态

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
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;

// 如果目标状态 小于 队首 Observer 的状态,则向后同步
if (mState.compareTo(mObserverMap.eldest().getValue().mState) < 0) {
backwardPass(lifecycleOwner);
}

// 如果目标状态 大于 队尾 Observer 的状态,则向前同步
Entry<LifecycleObserver, ObserverWithState> newest = mObserverMap.newest();
if (!mNewEventOccurred && newest != null
&& mState.compareTo(newest.getValue().mState) > 0) {
forwardPass(lifecycleOwner);
}

// 举个例子: 如果队列状态是 [4, 4, 3, 2, 1],目标状态是 3,经过 backwardPass(),状态队列变为 [3, 3, 3, 2, 1],
// 经过 forwardPass() 状态队列会变成 [3, 3, 3, 3, 3],此时同步完成,isSynced() 为 true,跳出循环
}
mNewEventOccurred = 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 void backwardPass(LifecycleOwner lifecycleOwner) {
// 从后往前遍历的 Iterator
Iterator<Entry<LifecycleObserver, ObserverWithState>> descendingIterator =
mObserverMap.descendingIterator();
while (descendingIterator.hasNext() && !mNewEventOccurred) {
Entry<LifecycleObserver, ObserverWithState> entry = descendingIterator.next();
ObserverWithState observer = entry.getValue();
// 当 observer 当前 state 值大于目标 state,且没有新事件触发,则触发循环
while ((observer.mState.compareTo(mState) > 0 && !mNewEventOccurred
&& mObserverMap.contains(entry.getKey()))) {
// 通过 downEvent() 将 observer 当前的 状态 向下转换成对应的 Event
Event event = downEvent(observer.mState);
pushParentState(getStateAfter(event));
// 分发 Event 事件
observer.dispatchEvent(lifecycleOwner, event);
popParentState();
}
}
}

private void forwardPass(LifecycleOwner lifecycleOwner) {
// 从前往后遍历
Iterator<Entry<LifecycleObserver, ObserverWithState>> ascendingIterator =
mObserverMap.iteratorWithAdditions();
while (ascendingIterator.hasNext() && !mNewEventOccurred) {
Entry<LifecycleObserver, ObserverWithState> entry = ascendingIterator.next();
ObserverWithState observer = entry.getValue();
while ((observer.mState.compareTo(mState) < 0 && !mNewEventOccurred
&& mObserverMap.contains(entry.getKey()))) {
pushParentState(observer.mState);
// 通过 upEvent() 将 observer 当前的 状态 向上转换成对应的 Event
// 并发送该 Event 事件
observer.dispatchEvent(lifecycleOwner, upEvent(observer.mState));
popParentState();
}
}
}

ObserverWithState#dispatchEvent :

1
2
3
4
5
6
7
8
9
10
static class ObserverWithState {
void dispatchEvent(LifecycleOwner owner, Event event) {
// 获取事件发生之后对应的状态
State newState = getStateAfter(event);
mState = min(mState, newState);
// 发送指定事件
mLifecycleObserver.onStateChanged(owner, event);
mState = newState;
}
}

这里的 mLifecycleObserver 即我们之前分析的 Lifecycling.lifecycleEventObserver() 返回的 Observer