This page looks best with JavaScript enabled

LifeCycle 原理

 ·  ☕ 4 min read

LifeCycle Android 架构组件。

其目的是: 方便开发者能从 Activity Fragment 的生命周期回调中解放,让开发者能自由的创建监听生命周期回调的组件。

@startuml

skinparam backgroundColor #EEEBDC
skinparam roundcorner 20

interface LifecycleOwner{
+ Lifecycle getLifecycle();
}

abstract class Lifecycle {
+ {abstract} void addObserver(LifecycleObserver observer)
+ {abstract} void removeObserver(LifecycleObserver observer)
+ {abstract} State getCurrentState()
}

class LifecycleRegistry extends Lifecycle{
+ void handleLifecycleEvent(Lifecycle.Event event)
}

enum Event {
    ON_CREATE,
    ON_START,
    ON_RESUME,
    ON_PAUSE,
    ON_STOP,
    ON_DESTROY,
    ON_ANY
}

enum State {
    DESTROYED,
    INITIALIZED,
    CREATED,
    STARTED,
    RESUMED;
}

interface LifecycleObserver

interface GenericLifecycleObserver extends LifecycleObserver {
+ void onStateChanged(LifecycleOwner source, Lifecycle.Event event);
}

class ReflectiveGenericLifecycleObserver implements GenericLifecycleObserver {
- Object mWrapped;
- CallbackInfo mInfo;
}

'LifecycleOwner 依赖 Lifecycle
LifecycleOwner ..> Lifecycle

class SupportActivity implements LifecycleOwner{
- LifecycleRegistry mLifecycleRegistry
}

'Lifecycle --- Event
'Lifecycle --- State

Lifecycle ..o LifecycleObserver

class ReportFragment{
- void dispatch(Lifecycle.Event event)
}

SupportActivity ..> ReportFragment
SupportActivity ..> LifecycleRegistry
ReportFragment ..> LifecycleRegistry
ReportFragment --o Event
LifecycleRegistry ..> Event
LifecycleRegistry --o State

@enduml

Lifecycle

一个抽象类,表示具有 Android 生命周期的对象。其能够被 LifecycleObserver 所观察,当生命周期发生改变时,能通知到 LifecycleObserver

LifecycleOwner

一个接口,表示拥有 Lifecycle 的对象。

LifecycleObserver

一个接口,表示生命周期的观察者,当生命周期发生改变时,将会收到通知。

原理

首先,Lifecycle 并没有改变 Android SDK 中的原有代码,其只是在 support 包中扩展了 SupportActivity 的功能,加上了 Lifecycle。

接下来从 Activity 和 Fragment 两个方向分析 Lifecycle 的实现原理。

Activity 的生命周期监听

首先,因为 LifecycleOwner 是 Lifecycle 的拥有者,所以先查找 LifecycleOwner 的实现者。在 Android Studio 中 show usage of interface of LifecyclerOwner,然后过滤 scope 为 Only lib

可以看到 Activity 中,只有 SupportActivity 实现了这个接口。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
public class SupportActivity extends Activity implements LifecycleOwner {
    private LifecycleRegistry mLifecycleRegistry = new LifecycleRegistry(this);

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

    @Override
    public Lifecycle getLifecycle() {
        return mLifecycleRegistry;
    }
}

精简之后发现,SupportActivity 中实质只有上面的代码比较特殊。构造了一个 LifecycleRegistry 对象,其持有了该 Activity。 然后在 onCreate 的时候调用了 ReportFragment 的静态方法 injectIfNeededIn。在 getLifecycle 的方法中,返回了 LifecycleRegistry 对象。可见 LifecycleRegistry 一定继承了 Lifecycle。

ReportFragment

ReportFragment 是一个没有界面的 Fragment,它的作用应该就是在各个生命周期事件回调中,进行分发。

 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 class ReportFragment extends Fragment {
    private static final String REPORT_FRAGMENT_TAG = "android.arch.lifecycle"
            + ".LifecycleDispatcher.report_fragment_tag";

    public static void injectIfNeededIn(Activity activity) {
        // 添加到 Activity 的 Fragment Stack 中
        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 onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        //...
        dispatch(Lifecycle.Event.ON_CREATE);
    }

    @Override
    public void onStart() {
        super.onStart();
        //...
        dispatch(Lifecycle.Event.ON_START);
    }

    @Override
    public void onResume() {
        super.onResume();
        //...
        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);
    }
}

ReportFragmentinjectIfNeededIn 创建了一个 ReportFragment 对象,然后提交到了 Acyivity 中。它在自己的各个生命周期回调中将调用 dispatch 方法,进行生命周期事件的分发。

dispatch 方法

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
private void dispatch(Lifecycle.Event event) {
    // 获取当前 Activity
    Activity activity = getActivity();
    // 判断 Activity 实现的 LifecycleOwner 类型
    // LifecycleRegistryOwner 是已经 Deprecated 的接口
    if (activity instanceof LifecycleRegistryOwner) {
        ((LifecycleRegistryOwner) activity).getLifecycle().handleLifecycleEvent(event);
        return;
    }

    // 现在所有 AppCompatActivity 都是继承自 SupportActivity 的,所以都实现了 LifecycleOwner 接口
    // 从上面可以得知: SupportActivity 的 getLifecycler 方法返回的是一个 LifecycleRegistry 对象
    if (activity instanceof LifecycleOwner) {
        Lifecycle lifecycle = ((LifecycleOwner) activity).getLifecycle();
        if (lifecycle instanceof LifecycleRegistry) {
            // 调用 LifecycleRegistry 的 handleLifecycleEvent 方法,将生命周期事件的分发工作交到了 LifecycleRegistry
            ((LifecycleRegistry) lifecycle).handleLifecycleEvent(event);
        }
    }
}

LifecycleRegistry

 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
public class LifecycleRegistry extends Lifecycle {
    // FastSafeIterableMap 就看做能在遍历中删除元素的 Map
    // Key 是 LifecycleObserver 类型
    // Value 是 LifecycleRegistry 的内部类 ObserverWithState
    FastSafeIterableMap<LifecycleObserver, ObserverWithState> mObserverMap = new FastSafeIterableMap<>();

    int mAddingObserverCounter = 0; // 记录正在添加 Observer 的数量

    boolean mHandlingEvent = false; // 记录是否正在处理事件
    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.
    // Google translate:
    // 在执行此 onStart 方法期间,newObserver 应仅被带到 CREATED 状态。 我们对 mObserverMap 的不变性没有帮助,因为父观察者不再在 map 中。
    ArrayList<State> mParentStates = new ArrayList<>();
    // 存储当前的状态
    private State mState;

    private final WeakReference<LifecycleOwner> mLifecycleOwner;

    public LifecycleRegistry(@NonNull LifecycleOwner provider) {
        mLifecycleOwner = new WeakReference<>(provider);
        mState = INITIALIZED;
    }

    // 该方法会在 ReportFragment dispatch 事件时调用
    public void handleLifecycleEvent(@NonNull Lifecycle.Event event) {
        State next = getStateAfter(event);
        moveToState(next);
    }

    // 每个生命周期对应的状态
    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;
        // 如果正在处理事件或者正在添加 Observer,则忽略该次事件
        if (mHandlingEvent || mAddingObserverCounter != 0) {
            mNewEventOccurred = true;
            // we will figure out what to do on upper level.
            return;
        }
        mHandlingEvent = true;
        // 同步事件给观察者们
        sync();
        mHandlingEvent = false;
    }
}

sync

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
private void sync() {
    LifecycleOwner lifecycleOwner = mLifecycleOwner.get();
    if (lifecycleOwner == null) {
        Log.w(LOG_TAG, "LifecycleOwner is garbage collected, you shouldn't try dispatch new events from it.");
        return;
    }
    // 如果还没有同步,就进行
    while (!isSynced()) {
        mNewEventOccurred = false;
        // no need to check eldest for nullability, because isSynced does it for us.
        // State enum 的顺序是 DESTROYED,INITIALIZED,CREATED,STARTED,RESUMED
        // 所以 <0 就说明状态是从右到左的改变
        // 以下判断有些晦涩 -_-
        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;
}

事件分发

 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
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);
            // 调用 ObserverWithState 的 dispatchEvent
            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));
            // 调用 ObserverWithState 的 dispatchEvent
            observer.dispatchEvent(lifecycleOwner, event);
            popParentState();
        }
    }
}

ObserverWithState 是对 LifecycleObserver 的一个封装,每次 addObserver 时就会将添加的 LifecycleObserver 封装。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
static class ObserverWithState {
    State mState;
    GenericLifecycleObserver mLifecycleObserver;

    ObserverWithState(LifecycleObserver observer, State initialState) {
        // 从 LifecycleObser 中获取 GenericLifecycleObserver
        mLifecycleObserver = Lifecycling.getCallback(observer);
        mState = initialState;
    }

    // 事件分发时调用
    void dispatchEvent(LifecycleOwner owner, Event event) {
        State newState = getStateAfter(event);
        mState = min(mState, newState);
        // 调用 GenericLifecycleObserver 的 onStateChanged
        mLifecycleObserver.onStateChanged(owner, event);
        mState = newState;
    }
}
Support the author with
alipay QR Code
wechat QR Code

Yang
WRITTEN BY
Yang
Developer