Lifecycle 的实现

Lifecycle 隶属于 Android 官方架构组件,它的实现跟 ViewModel 类似,都是利用 Fragment 来实现它的功能。通过添加一个 fragment 到 activity 中,这个 fragment 便能够接收到各个生命周期回调。

使用方法简介

这里我并不打算讲太多 lifecycle 的用法,不熟悉的同学,可以阅读这篇[1]。

为了使用 lifecycle,首先需要获取到一个 LifecycleOwner。

 1lifecycleOwner.getLifecycle().addObserver(observer);
 2
 3public interface LifecycleOwner {
 4    /**
 5     * Returns the Lifecycle of the provider.
 6     *
 7     * @return The lifecycle of the provider.
 8     */
 9    @NonNull
10    Lifecycle getLifecycle();
11}

使用 support 包时,AppCompatActivity 就是一个 LifecycleOwner。具体的实现是 SupportActivity:

1public class SupportActivity extends Activity implements LifecycleOwner {}

下面,我们就从 SupportActivity 开始分析 lifecycle 组件的实现。

获取生命周期

 1public class SupportActivity extends Activity implements LifecycleOwner {
 2
 3    private LifecycleRegistry mLifecycleRegistry = new LifecycleRegistry(this);
 4
 5    @Override
 6    public Lifecycle getLifecycle() {
 7        return mLifecycleRegistry;
 8    }
 9
10    @Override
11    protected void onCreate(@Nullable Bundle savedInstanceState) {
12        super.onCreate(savedInstanceState);
13        // 初始化 ReportFragment
14        ReportFragment.injectIfNeededIn(this);
15    }
16}

可以看到,在上一节中我们执行 lifecycleOwner.getLifecycle() 返回的就是 mLifecycleRegistry。关于 LifecycleRegistry,我们在下一节再看,这里先看 ReportFragment。

ReportFragment 就是我们在一开始说的,用于获取生命周期的 fragment:

  1public class ReportFragment extends Fragment {
  2    private static final String REPORT_FRAGMENT_TAG = "android.arch.lifecycle"
  3            + ".LifecycleDispatcher.report_fragment_tag";
  4
  5    public static void injectIfNeededIn(Activity activity) {
  6        // ProcessLifecycleOwner should always correctly work and some activities may not extend
  7        // FragmentActivity from support lib, so we use framework fragments for activities
  8        android.app.FragmentManager manager = activity.getFragmentManager();
  9        if (manager.findFragmentByTag(REPORT_FRAGMENT_TAG) == null) {
 10            manager.beginTransaction().add(new ReportFragment(), REPORT_FRAGMENT_TAG).commit();
 11            // Hopefully, we are the first to make a transaction.
 12            manager.executePendingTransactions();
 13        }
 14    }
 15
 16    static ReportFragment get(Activity activity) {
 17        return (ReportFragment) activity.getFragmentManager().findFragmentByTag(
 18                REPORT_FRAGMENT_TAG);
 19    }
 20
 21    private ActivityInitializationListener mProcessListener;
 22
 23    private void dispatchCreate(ActivityInitializationListener listener) {
 24        if (listener != null) {
 25            listener.onCreate();
 26        }
 27    }
 28
 29    private void dispatchStart(ActivityInitializationListener listener) {
 30        if (listener != null) {
 31            listener.onStart();
 32        }
 33    }
 34
 35    private void dispatchResume(ActivityInitializationListener listener) {
 36        if (listener != null) {
 37            listener.onResume();
 38        }
 39    }
 40
 41    @Override
 42    public void onActivityCreated(Bundle savedInstanceState) {
 43        super.onActivityCreated(savedInstanceState);
 44        dispatchCreate(mProcessListener);
 45        dispatch(Lifecycle.Event.ON_CREATE);
 46    }
 47
 48    @Override
 49    public void onStart() {
 50        super.onStart();
 51        dispatchStart(mProcessListener);
 52        dispatch(Lifecycle.Event.ON_START);
 53    }
 54
 55    @Override
 56    public void onResume() {
 57        super.onResume();
 58        dispatchResume(mProcessListener);
 59        dispatch(Lifecycle.Event.ON_RESUME);
 60    }
 61
 62    @Override
 63    public void onPause() {
 64        super.onPause();
 65        dispatch(Lifecycle.Event.ON_PAUSE);
 66    }
 67
 68    @Override
 69    public void onStop() {
 70        super.onStop();
 71        dispatch(Lifecycle.Event.ON_STOP);
 72    }
 73
 74    @Override
 75    public void onDestroy() {
 76        super.onDestroy();
 77        dispatch(Lifecycle.Event.ON_DESTROY);
 78        // just want to be sure that we won't leak reference to an activity
 79        mProcessListener = null;
 80    }
 81
 82    private void dispatch(Lifecycle.Event event) {
 83        Activity activity = getActivity();
 84        if (activity instanceof LifecycleRegistryOwner) {
 85            ((LifecycleRegistryOwner) activity).getLifecycle().handleLifecycleEvent(event);
 86            return;
 87        }
 88
 89        // 对于 SupportActivity 来说,执行的是下面这个
 90        if (activity instanceof LifecycleOwner) {
 91            Lifecycle lifecycle = ((LifecycleOwner) activity).getLifecycle();
 92            if (lifecycle instanceof LifecycleRegistry) {
 93                ((LifecycleRegistry) lifecycle).handleLifecycleEvent(event);
 94            }
 95        }
 96    }
 97
 98    void setProcessListener(ActivityInitializationListener processListener) {
 99        mProcessListener = processListener;
100    }
101
102    interface ActivityInitializationListener {
103        void onCreate();
104
105        void onStart();
106
107        void onResume();
108    }
109}

ReportFragment 的实现很简单,读者自己看看就好。下面我们开始看不那么好理解的 LifecycleRegistry。

生命周期事件的分发

在看代码前,我们先来了解一下 Lifecycle 的状态和事件:

 1public abstract class Lifecycle {
 2
 3    public enum Event {
 4        /**
 5         * Constant for onCreate event of the {@link LifecycleOwner}.
 6         */
 7        ON_CREATE,
 8        /**
 9         * Constant for onStart event of the {@link LifecycleOwner}.
10         */
11        ON_START,
12        /**
13         * Constant for onResume event of the {@link LifecycleOwner}.
14         */
15        ON_RESUME,
16        /**
17         * Constant for onPause event of the {@link LifecycleOwner}.
18         */
19        ON_PAUSE,
20        /**
21         * Constant for onStop event of the {@link LifecycleOwner}.
22         */
23        ON_STOP,
24        /**
25         * Constant for onDestroy event of the {@link LifecycleOwner}.
26         */
27        ON_DESTROY,
28        /**
29         * An {@link Event Event} constant that can be used to match all events.
30         */
31        ON_ANY
32    }
33
34    /**
35     * Lifecycle states. You can consider the states as the nodes in a graph and
36     * {@link Event}s as the edges between these nodes.
37     */
38    public enum State {
39        /**
40         * Destroyed state for a LifecycleOwner. After this event, this Lifecycle will not dispatch
41         * any more events. For instance, for an {@link android.app.Activity}, this state is reached
42         * <b>right before</b> Activity's {@link android.app.Activity#onDestroy() onDestroy} call.
43         */
44        DESTROYED,
45
46        /**
47         * Initialized state for a LifecycleOwner. For an {@link android.app.Activity}, this is
48         * the state when it is constructed but has not received
49         * {@link android.app.Activity#onCreate(android.os.Bundle) onCreate} yet.
50         */
51        INITIALIZED,
52
53        /**
54         * Created state for a LifecycleOwner. For an {@link android.app.Activity}, this state
55         * is reached in two cases:
56         * <ul>
57         *     <li>after {@link android.app.Activity#onCreate(android.os.Bundle) onCreate} call;
58         *     <li><b>right before</b> {@link android.app.Activity#onStop() onStop} call.
59         * </ul>
60         */
61        CREATED,
62
63        /**
64         * Started state for a LifecycleOwner. For an {@link android.app.Activity}, this state
65         * is reached in two cases:
66         * <ul>
67         *     <li>after {@link android.app.Activity#onStart() onStart} call;
68         *     <li><b>right before</b> {@link android.app.Activity#onPause() onPause} call.
69         * </ul>
70         */
71        STARTED,
72
73        /**
74         * Resumed state for a LifecycleOwner. For an {@link android.app.Activity}, this state
75         * is reached after {@link android.app.Activity#onResume() onResume} is called.
76         */
77        RESUMED;
78
79        /**
80         * Compares if this State is greater or equal to the given {@code state}.
81         *
82         * @param state State to compare with
83         * @return true if this State is greater or equal to the given {@code state}
84         */
85        public boolean isAtLeast(@NonNull State state) {
86            return compareTo(state) >= 0;
87        }
88    }
89}

Lifecycle.Event 对应 activity 的各个声明周期,State 则是 Lifecycle 的状态。在 LifecycleRegistry 中定义了状态间的转化关系:

 1public class LifecycleRegistry extends Lifecycle {
 2
 3    static State getStateAfter(Event event) {
 4        switch (event) {
 5            case ON_CREATE:
 6            case ON_STOP:
 7                return CREATED;
 8            case ON_START:
 9            case ON_PAUSE:
10                return STARTED;
11            case ON_RESUME:
12                return RESUMED;
13            case ON_DESTROY:
14                return DESTROYED;
15            case ON_ANY:
16                break;
17        }
18        throw new IllegalArgumentException("Unexpected event value " + event);
19    }
20
21    private static Event downEvent(State state) {
22        switch (state) {
23            case INITIALIZED:
24                throw new IllegalArgumentException();
25            case CREATED:
26                return ON_DESTROY;
27            case STARTED:
28                return ON_STOP;
29            case RESUMED:
30                return ON_PAUSE;
31            case DESTROYED:
32                throw new IllegalArgumentException();
33        }
34        throw new IllegalArgumentException("Unexpected state value " + state);
35    }
36
37    private static Event upEvent(State state) {
38        switch (state) {
39            case INITIALIZED:
40            case DESTROYED:
41                return ON_CREATE;
42            case CREATED:
43                return ON_START;
44            case STARTED:
45                return ON_RESUME;
46            case RESUMED:
47                throw new IllegalArgumentException();
48        }
49        throw new IllegalArgumentException("Unexpected state value " + state);
50    }
51}

这三个方法,可以总结为下面这样一张图:

android-arch-lifecycle-states

downEvent 在图中表示从一个状态到他下面的那个状态,upEvent 则是往上。

了解了 Lifecycle 的状态后,我们继续来看 LifecycleRegistry。上一节我们知道,activity 的生命周期发生变化后,会调用到 LifecycleRegistry 的 handleLifecycleEvent:

 1public class LifecycleRegistry extends Lifecycle {
 2
 3    private int mAddingObserverCounter = 0;
 4
 5    private boolean mHandlingEvent = false;
 6    private boolean mNewEventOccurred = false;
 7
 8    public void handleLifecycleEvent(@NonNull Lifecycle.Event event) {
 9        State next = getStateAfter(event);
10        moveToState(next);
11    }
12
13    private void moveToState(State next) {
14        if (mState == next) {
15            return;
16        }
17        mState = next;
18        // 当我们在 LifecycleRegistry 回调 LifecycleObserver 的时候触发状态变化时,
19        // mHandlingEvent 为 true;
20        // 添加 observer 的时候,也可能会执行回调方法,这时候如果触发了状态变化,
21        // 则 mAddingObserverCounter != 0
22        if (mHandlingEvent || mAddingObserverCounter != 0) {
23            mNewEventOccurred = true;
24            // 不需要执行 sync。
25            // 执行到这里的情况是:sync() -> LifecycleObserver -> moveToState()
26            // 这里直接返回后,还是会回到 sync(),然后继续同步状态给 observer
27            // we will figure out what to do on upper level.
28            return;
29        }
30        mHandlingEvent = true;
31        // sync() 会把状态的变化转化为生命周期事件,然后转发给 LifecycleObserver
32        sync();
33        mHandlingEvent = false;
34    }
35}

LifecycleRegistry 本来要做的事其实是很简单的,但由于他需要执行客户的代码,由此引入了很多额外的复杂度。原因是,客户代码并不处在我们的控制之下,他们可能做出任何可以做到的事。例如这里,在回调中又触发状态变化。类似的情况是,在持有锁的时候不调用客户代码,这个也会让实现变得比较复杂。

接下来我们看 sync():

 1public class LifecycleRegistry extends Lifecycle {
 2
 3    /**
 4     * Custom list that keeps observers and can handle removals / additions during traversal.
 5     *
 6     * 这个 Invariant 非常重要,他会影响到 sync() 的逻辑
 7     * Invariant: at any moment of time for observer1 & observer2:
 8     * if addition_order(observer1) < addition_order(observer2), then
 9     * state(observer1) >= state(observer2),
10     */
11    private FastSafeIterableMap<LifecycleObserver, ObserverWithState> mObserverMap =
12            new FastSafeIterableMap<>();
13
14
15    // happens only on the top of stack (never in reentrance),
16    // so it doesn't have to take in account parents
17    private void sync() {
18        LifecycleOwner lifecycleOwner = mLifecycleOwner.get();
19        if (lifecycleOwner == null) {
20            Log.w(LOG_TAG, "LifecycleOwner is garbage collected, you shouldn't try dispatch "
21                    + "new events from it.");
22            return;
23        }
24        while (!isSynced()) {
25            // mNewEventOccurred 是为了在 observer 触发状态变化时让 backwardPass/forwardPass()
26            // 提前返回用的。我们刚准备调他们,这里设置为 false 即可。
27            mNewEventOccurred = false;
28            // no need to check eldest for nullability, because isSynced does it for us.
29            if (mState.compareTo(mObserverMap.eldest().getValue().mState) < 0) {
30                // mObserverMap 里的元素的状态是非递增排列的,也就是说,队头的 state 最大
31                // 如果 mState 小于队列里最大的那个,说明有元素需要更新状态
32                // 为了维持 mObserverMap 的 Invariant,这里我们需要从队尾往前更新元素的状态
33                backwardPass(lifecycleOwner);
34            }
35            Entry<LifecycleObserver, ObserverWithState> newest = mObserverMap.newest();
36            // 如果 mNewEventOccurred,说明在上面调用 backwardPass() 时,客户触发了状态修改
37            if (!mNewEventOccurred && newest != null
38                    && mState.compareTo(newest.getValue().mState) > 0) {
39                forwardPass(lifecycleOwner);
40            }
41        }
42        mNewEventOccurred = false;
43    }
44
45    // 如果所有的 observer 的状态都已经同步完,则返回 true
46    private boolean isSynced() {
47        if (mObserverMap.size() == 0) {
48            return true;
49        }
50        State eldestObserverState = mObserverMap.eldest().getValue().mState;
51        State newestObserverState = mObserverMap.newest().getValue().mState;
52        // 因为我们保证队头的 state >= 后面的元素的 state,所以只要判断头尾就够了
53        return eldestObserverState == newestObserverState && mState == newestObserverState;
54    }
55
56}

sync() 的主要作用就是根据把 mObserverMap 里所有元素的状态都同步为 mState。我们继续看剩下的 backwardPass/forwardPass:

 1public class LifecycleRegistry extends Lifecycle {
 2
 3    private ArrayList<State> mParentStates = new ArrayList<>();
 4
 5
 6    private void forwardPass(LifecycleOwner lifecycleOwner) {
 7        // 从队头开始迭代
 8        Iterator<Entry<LifecycleObserver, ObserverWithState>> ascendingIterator =
 9                mObserverMap.iteratorWithAdditions();
10        while (ascendingIterator.hasNext() && !mNewEventOccurred) {
11            Entry<LifecycleObserver, ObserverWithState> entry = ascendingIterator.next();
12            ObserverWithState observer = entry.getValue();
13            while ((observer.mState.compareTo(mState) < 0 && !mNewEventOccurred
14                    // 可能在回调客户代码的时候,客户把自己移除了
15                    && mObserverMap.contains(entry.getKey()))) {
16                // pushParentState 和 popParentState 我们下一小节再看,这里先忽略
17                pushParentState(observer.mState);
18                observer.dispatchEvent(lifecycleOwner, upEvent(observer.mState));
19                popParentState();
20            }
21        }
22    }
23
24    private void backwardPass(LifecycleOwner lifecycleOwner) {
25        // 从队尾开始迭代
26        Iterator<Entry<LifecycleObserver, ObserverWithState>> descendingIterator =
27                mObserverMap.descendingIterator();
28        while (descendingIterator.hasNext() && !mNewEventOccurred) {
29            Entry<LifecycleObserver, ObserverWithState> entry = descendingIterator.next();
30            ObserverWithState observer = entry.getValue();
31            while ((observer.mState.compareTo(mState) > 0 && !mNewEventOccurred
32                    && mObserverMap.contains(entry.getKey()))) {
33                Event event = downEvent(observer.mState);
34                pushParentState(getStateAfter(event));
35                observer.dispatchEvent(lifecycleOwner, event);
36                popParentState();
37            }
38        }
39    }
40
41    private void popParentState() {
42        mParentStates.remove(mParentStates.size() - 1);
43    }
44
45    private void pushParentState(State state) {
46        mParentStates.add(state);
47    }
48}

在看这两个方法时,可以参考上面的状态图。比方说,假设当前队列里的元素都处于 CREATED。接着收到了一个 ON_START 事件,从图里面可以看出,接下来应该是要到 STARTED 状态。由于 STARTED 大于 CREATED,所以会执行 forwardPass()。forwardPass() 里面调用 upEvent(observer.mState),返回从 CREATED 往上到 STARTED 需要发送的事件,也就是 ON_START,于是 ON_START 事件发送给了客户。

注册/注销 observer

注册 observer 由 addObserver 方法完成:

 1public class LifecycleRegistry extends Lifecycle {
 2
 3    // 这段注释应该是这整个类里面最难理解的了吧,至少对于我来说是这样
 4    // we have to keep it for cases:
 5    // void onStart() {
 6    //     // removeObserver(this),说明 this 是一个 LifecycleObserver
 7    //     // 所以这里说的是,我们在回调里执行了下面两个操作
 8    //     mRegistry.removeObserver(this);
 9    //     mRegistry.add(newObserver);
10    // }
11    // 假定现在我们要从 CREATED 转到 STARTED 状态(也就是说,mState 现在是 STARTED)。
12    // 这种情况下,只有将新的 observer 设置为 CREATED 状态,它的 onStart 才会被调用
13    // 为了得到这个 CREATED,在这里才引入了 mParentStates。在 forwardPass 中执行
14    // pushParentState(observer.mState) 时,observer.mState 就是我们需要的 CREATED。
15    // backwardPass 的情况类似。
16    // newObserver should be brought only to CREATED state during the execution of
17    // this onStart method. our invariant with mObserverMap doesn't help, because parent observer
18    // is no longer in the map.
19    private ArrayList<State> mParentStates = new ArrayList<>();
20
21
22    private State calculateTargetState(LifecycleObserver observer) {
23        Entry<LifecycleObserver, ObserverWithState> previous = mObserverMap.ceil(observer);
24
25        State siblingState = previous != null ? previous.getValue().mState : null;
26        State parentState = !mParentStates.isEmpty() ? mParentStates.get(mParentStates.size() - 1)
27                : null;
28        // 返回最小的 state
29        return min(min(mState, siblingState), parentState);
30    }
31
32    @Override
33    public void addObserver(@NonNull LifecycleObserver observer) {
34        State initialState = mState == DESTROYED ? DESTROYED : INITIALIZED;
35        ObserverWithState statefulObserver = new ObserverWithState(observer, initialState);
36        ObserverWithState previous = mObserverMap.putIfAbsent(observer, statefulObserver);
37
38        if (previous != null) {
39            return;
40        }
41
42        LifecycleOwner lifecycleOwner = mLifecycleOwner.get();
43        if (lifecycleOwner == null) {
44            // it is null we should be destroyed. Fallback quickly
45            return;
46        }
47
48        // 在回调中执行了 addObserver()
49        boolean isReentrance = mAddingObserverCounter != 0 || mHandlingEvent;
50        State targetState = calculateTargetState(observer);
51        mAddingObserverCounter++;
52        while ((statefulObserver.mState.compareTo(targetState) < 0
53                && mObserverMap.contains(observer))) {
54            pushParentState(statefulObserver.mState);
55            statefulObserver.dispatchEvent(lifecycleOwner, upEvent(statefulObserver.mState));
56            popParentState();
57            // 我们 dispatch 了一个事件给客户,在回调客户代码的时候,客户可能会修改我们的状态
58            // mState / subling may have been changed recalculate
59            targetState = calculateTargetState(observer);
60        }
61
62        if (!isReentrance) {
63            // we do sync only on the top level.
64            sync();
65        }
66        mAddingObserverCounter--;
67    }
68
69
70    static class ObserverWithState {
71        State mState;
72        GenericLifecycleObserver mLifecycleObserver;
73
74        ObserverWithState(LifecycleObserver observer, State initialState) {
75            mLifecycleObserver = Lifecycling.getCallback(observer);
76            mState = initialState;
77        }
78
79        void dispatchEvent(LifecycleOwner owner, Event event) {
80            State newState = getStateAfter(event);
81            mState = min(mState, newState);
82            mLifecycleObserver.onStateChanged(owner, event);
83            mState = newState;
84        }
85    }
86}

由于篇幅有限,这里的 Lifecycling.getCallback 就不看了。简单提一下,在使用 annotion 的时候,对应的 observer 会生成一个 adapter,这个 adapter 会把对应的 Lifecycle.Event 装换为方法调用:

 1static class BoundLocationListener implements LifecycleObserver {
 2    @OnLifecycleEvent(Lifecycle.Event.ON_RESUME)
 3    void addLocationListener() {}
 4
 5    @OnLifecycleEvent(Lifecycle.Event.ON_PAUSE)
 6    void removeLocationListener() {}
 7}
 8
 9// 生成的代码
10public class BoundLocationManager_BoundLocationListener_LifecycleAdapter implements GeneratedAdapter {
11  final BoundLocationManager.BoundLocationListener mReceiver;
12
13  BoundLocationManager_BoundLocationListener_LifecycleAdapter(BoundLocationManager.BoundLocationListener receiver) {
14    this.mReceiver = receiver;
15  }
16
17  @Override
18  public void callMethods(LifecycleOwner owner, Lifecycle.Event event, boolean onAny,
19      MethodCallsLogger logger) {
20    boolean hasLogger = logger != null;
21    if (onAny) {
22      return;
23    }
24    if (event == Lifecycle.Event.ON_RESUME) {
25      if (!hasLogger || logger.approveCall("addLocationListener", 1)) {
26        mReceiver.addLocationListener();
27      }
28      return;
29    }
30    if (event == Lifecycle.Event.ON_PAUSE) {
31      if (!hasLogger || logger.approveCall("removeLocationListener", 1)) {
32        mReceiver.removeLocationListener();
33      }
34      return;
35    }
36  }
37}

注销 observer 的实现就比较简单了:

 1public class LifecycleRegistry extends Lifecycle {
 2    @Override
 3    public void removeObserver(@NonNull LifecycleObserver observer) {
 4        // we consciously decided not to send destruction events here in opposition to addObserver.
 5        // Our reasons for that:
 6        // 1. These events haven't yet happened at all. In contrast to events in addObservers, that
 7        // actually occurred but earlier.
 8        // 2. There are cases when removeObserver happens as a consequence of some kind of fatal
 9        // event. If removeObserver method sends destruction events, then a clean up routine becomes
10        // more cumbersome. More specific example of that is: your LifecycleObserver listens for
11        // a web connection, in the usual routine in OnStop method you report to a server that a
12        // session has just ended and you close the connection. Now let's assume now that you
13        // lost an internet and as a result you removed this observer. If you get destruction
14        // events in removeObserver, you should have a special case in your onStop method that
15        // checks if your web connection died and you shouldn't try to report anything to a server.
16        mObserverMap.remove(observer);
17    }
18}

恭喜你,相信你现在对 lifecycle 的实现已经胸有成竹,可以愉快地装逼了。

附:
[1] https://developer.android.google.cn/topic/libraries/architecture/

猜你喜欢

转载自blog.csdn.net/jiang19921002/article/details/81280205