1 前言

前一篇博文已经初步的介绍了Android Architecture Components的基本概念以及基本使用,相信大家已经对这个组件有了一定的了解,这一篇博文主要来解析Android Architecture Components 的Lifecycles生命周期组件,以便于大家更好的深入理解这个组件。从而更好的进行App架构设计。

2 Lifecycles 的作用

生命周期管理(Lifecycles)组件,官方解释是帮助开发者创建 “可感知生命周期的” 组件,让其自己管理自己的生命周期,从而减少内存泄露和崩溃的可能性。参考
https://developer.android.google.cn/topic/libraries/architecture/lifecycle.html

从官方的说明知道,Lifecycles的作用是监测Activity/Fragment等生命周期组件在生命周期变化时,能及时通知其他组件。
在Lifecycles出现以前,我们需要手动的在Activity/Fragment的生命周期中通知其他组件,并且往往会定义基类的Activity/Fragment来达到代码复用的目的。在传统的MVP中,Activity/Fragment充当了V的角色,由于引用了P,为了防止空指针引用和减少内存泄漏,我们都会在V层的生命周期中回调P,从而避免这些问题,这些代码往往会被定义层基类及泛型。对开发者的开发能力增加了一定的要求。google应该是看到了传统的Activity/Fragment的这些缺陷,从而发布了这个Android Architecture Components 来改善Android 程序的开发。
在android support组件升级到26.1.0之后,Fragment和FragmentActivity都已经默认实现了Lifecycles接口,相信在不久的将来,Activity也会实现Lifecycles接口

Fragment 实现了LifecycleOwner 接口

public class Fragment implements ComponentCallbacks, OnCreateContextMenuListener, LifecycleOwner {
    private static final SimpleArrayMap<String, Class<?>> sClassMap =
            new SimpleArrayMap<String, Class<?>>();
.....

SupportActivity 实现了LifecycleOwner 接口

public class SupportActivity extends Activity implements LifecycleOwner {
    /**
     * Storage for {@link ExtraData} instances.
     *
     * <p>Note that these objects are not retained across configuration changes</p>
     */
    private SimpleArrayMap<Class<? extends ExtraData>, ExtraData> mExtraDataMap =
            new SimpleArrayMap<>();

    private LifecycleRegistry mLifecycleRegistry = new LifecycleRegistry(this);


.....
public class FragmentActivity extends BaseFragmentActivityApi16 implements
        ActivityCompat.OnRequestPermissionsResultCallback,
        ActivityCompat.RequestPermissionsRequestCodeValidator {
    private static final String TAG = "FragmentActivity";

FragmentActivity 最终会继承SupportActivity ,都会实现LifecycleOwner 接口

这样,Google从官方上解决了Activity/Fragment在生命周期变化时,其他组件之前无法感知的问题。

3 Lifecycles 类图

Lifecycles 组件涉及到的类和接口并不多,大多数都在android.arch.lifecycle这个包下,查看源码,我们可以画出如下的UML类图

android 如何查看 architecture android architecture components_Android架构组件


可以看到,包含以下几个重要的类

LifecycleOwner 接口

@SuppressWarnings({"WeakerAccess", "unused"})
public interface LifecycleOwner {
    /**
     * Returns the Lifecycle of the provider.
     *
     * @return The lifecycle of the provider.
     */
    @NonNull
    Lifecycle getLifecycle();
}

该接口返回一个Lifecycle 对象,Activity/Fragment都需要实现该接口,这样Activity/Fragment都会有自己的Lifecycle 的对象了

Lifecycle

public abstract class Lifecycle {
    /**
     * Adds a LifecycleObserver that will be notified when the LifecycleOwner changes
     * state.
     * <p>
     * The given observer will be brought to the current state of the LifecycleOwner.
     * For example, if the LifecycleOwner is in {@link State#STARTED} state, the given observer
     * will receive {@link Event#ON_CREATE}, {@link Event#ON_START} events.
     *
     * @param observer The observer to notify.
     */
    @MainThread
    public abstract void addObserver(@NonNull LifecycleObserver observer);

    /**
     * Removes the given observer from the observers list.
     * <p>
     * If this method is called while a state change is being dispatched,
     * <ul>
     * <li>If the given observer has not yet received that event, it will not receive it.
     * <li>If the given observer has more than 1 method that observes the currently dispatched
     * event and at least one of them received the event, all of them will receive the event and
     * the removal will happen afterwards.
     * </ul>
     *
     * @param observer The observer to be removed.
     */
    @MainThread
    public abstract void removeObserver(@NonNull LifecycleObserver observer);

    /**
     * Returns the current state of the Lifecycle.
     *
     * @return The current state of the Lifecycle.
     */
    @MainThread
    public abstract State getCurrentState();

    @SuppressWarnings("WeakerAccess")
    public enum Event {
        /**
         * Constant for onCreate event of the {@link LifecycleOwner}.
         */
        ON_CREATE,
        /**
         * Constant for onStart event of the {@link LifecycleOwner}.
         */
        ON_START,
        /**
         * Constant for onResume event of the {@link LifecycleOwner}.
         */
        ON_RESUME,
        /**
         * Constant for onPause event of the {@link LifecycleOwner}.
         */
        ON_PAUSE,
        /**
         * Constant for onStop event of the {@link LifecycleOwner}.
         */
        ON_STOP,
        /**
         * Constant for onDestroy event of the {@link LifecycleOwner}.
         */
        ON_DESTROY,
        /**
         * An {@link Event Event} constant that can be used to match all events.
         */
        ON_ANY
    }

    /**
     * Lifecycle states. You can consider the states as the nodes in a graph and
     * {@link Event}s as the edges between these nodes.
     */
    @SuppressWarnings("WeakerAccess")
    public enum State {
        /**
         * Destroyed state for a LifecycleOwner. After this event, this Lifecycle will not dispatch
         * any more events. For instance, for an {@link android.app.Activity}, this state is reached
         * <b>right before</b> Activity's {@link android.app.Activity#onDestroy() onDestroy} call.
         */
        DESTROYED,

        /**
         * Initialized state for a LifecycleOwner. For an {@link android.app.Activity}, this is
         * the state when it is constructed but has not received
         * {@link android.app.Activity#onCreate(android.os.Bundle) onCreate} yet.
         */
        INITIALIZED,

        /**
         * Created state for a LifecycleOwner. For an {@link android.app.Activity}, this state
         * is reached in two cases:
         * <ul>
         *     <li>after {@link android.app.Activity#onCreate(android.os.Bundle) onCreate} call;
         *     <li><b>right before</b> {@link android.app.Activity#onStop() onStop} call.
         * </ul>
         */
        CREATED,

        /**
         * Started state for a LifecycleOwner. For an {@link android.app.Activity}, this state
         * is reached in two cases:
         * <ul>
         *     <li>after {@link android.app.Activity#onStart() onStart} call;
         *     <li><b>right before</b> {@link android.app.Activity#onPause() onPause} call.
         * </ul>
         */
        STARTED,

        /**
         * Resumed state for a LifecycleOwner. For an {@link android.app.Activity}, this state
         * is reached after {@link android.app.Activity#onResume() onResume} is called.
         */
        RESUMED;

        /**
         * Compares if this State is greater or equal to the given {@code state}.
         *
         * @param state State to compare with
         * @return true if this State is greater or equal to the given {@code state}
         */
        public boolean isAtLeast(@NonNull State state) {
            return compareTo(state) >= 0;
        }
    }
}

Lifecycle对象提供了添加和移除LifecycleObserver的接口,

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

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

    @MainThread
    public abstract State getCurrentState();

这里运用了观察者模式,将Activity/Fragment的状态作为被观察者,提供给感兴趣的观察者组件。

另外,Lifecycle里面有两个内部枚举类Event和State

Event共有7个类型,分别对应于Activity/Fragment的onCreate() – onDestory(),其中ON_ANY表示匹配任一生命周期

State根据注释的解释如下:

DESTROYED:在Activity/Fragment将要回调onDestory()时,该状态之后Lifecycle将不会分发任何事件

**INITIALIZED:**Activity/Fragment被创建实例,但是还没有回调onCreate()方法,作为一个初始状态

CREATED:两种情况,一是在Activity/Fragment回调onCreate()之后,onStart()之前。二是在onStop()回调之前的状态

STARTED:两种情况,一是在Activity/Fragment回调onStart()之后,onResume()之前。二是在onPause()回调之前的状态

RESUMED:在Activity/Fragment回调onResume()之后的状态

关于State与Event之间的状态转化,可以用官方的如下图表示

android 如何查看 architecture android architecture components_Android架构组件_02

另外Lifecycle是一个抽象类,具体的实现是在LifecycleRegistry 类中

public class LifecycleRegistry extends Lifecycle {

    private static final String LOG_TAG = "LifecycleRegistry";

    /**
     * Custom list that keeps observers and can handle removals / additions during traversal.
     *
     * Invariant: at any moment of time for observer1 & observer2:
     * if addition_order(observer1) < addition_order(observer2), then
     * state(observer1) >= state(observer2),
     */
    private FastSafeIterableMap<LifecycleObserver, ObserverWithState> mObserverMap =
            new FastSafeIterableMap<>();
    /**
     * Current state
     */
    private State mState;
    /**
     * The provider that owns this Lifecycle.
     * Only WeakReference on LifecycleOwner is kept, so if somebody leaks Lifecycle, they won't leak
     * the whole Fragment / Activity. However, to leak Lifecycle object isn't great idea neither,
     * because it keeps strong references on all other listeners, so you'll leak all of them as
     * well.
     */
    private final WeakReference<LifecycleOwner> mLifecycleOwner;

    private int mAddingObserverCounter = 0;

    private boolean mHandlingEvent = false;
    private 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.
    private ArrayList<State> mParentStates = new ArrayList<>();

    /**
     * Creates a new LifecycleRegistry for the given provider.
     * <p>
     * You should usually create this inside your LifecycleOwner class's constructor and hold
     * onto the same instance.
     *
     * @param provider The owner LifecycleOwner
     */
    public LifecycleRegistry(@NonNull LifecycleOwner provider) {
        mLifecycleOwner = new WeakReference<>(provider);
        mState = INITIALIZED;
    }

    /**
     * Moves the Lifecycle to the given state and dispatches necessary events to the observers.
     *
     * @param state new state
     */
    @SuppressWarnings("WeakerAccess")
    @MainThread
    public void markState(@NonNull State state) {
        moveToState(state);
    }

    /**
     * Sets the current state and notifies the observers.
     * <p>
     * Note that if the {@code currentState} is the same state as the last call to this method,
     * calling this method has no effect.
     *
     * @param event The event that was received
     */
    public void handleLifecycleEvent(@NonNull Lifecycle.Event event) {
        State next = getStateAfter(event);
        moveToState(next);
    }

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

    .....
    @Override
    public void addObserver(@NonNull LifecycleObserver observer) {
        State initialState = mState == DESTROYED ? DESTROYED : INITIALIZED;
        ObserverWithState statefulObserver = new ObserverWithState(observer, initialState);
        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++;
        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.
            sync();
        }
        mAddingObserverCounter--;
    }

    ....

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

    /**
     * The number of observers.
     *
     * @return The number of observers.
     */
    @SuppressWarnings("WeakerAccess")
    public int getObserverCount() {
        return mObserverMap.size();
    }

    @Override
    public State getCurrentState() {
        return mState;
    }

    .....

        static class ObserverWithState {
        State mState;
        GenericLifecycleObserver mLifecycleObserver;

        ObserverWithState(LifecycleObserver observer, State initialState) {
            mLifecycleObserver = Lifecycling.getCallback(observer);
            mState = initialState;
        }

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

这里列出来主要的一些接口实现,其他的可以参考源码来阅读,在Activity/Fragment中返回的Lifecycle就是返回LifecycleRegistry

LifecycleObserver

public interface LifecycleObserver {

}

LifecycleObserver 是一个空接口,Activity和Fragment的实现是在GenericLifecycleObserver 接口

public interface GenericLifecycleObserver extends LifecycleObserver {
    /**
     * Called when a state transition event happens.
     *
     * @param source The source of the event
     * @param event The event
     */
    void onStateChanged(LifecycleOwner source, Lifecycle.Event event);
}

可以看到,这里面有一个onStateChanged(LifecycleOwner source, Lifecycle.Event event)方法,这样当Lifecycle组件生命周期变化时,就可以通知LifecycleObserver 的Lifecycle.Event 变化了。

了解了以上的内容,我们从以下几个方面来分析LifeCycles组件的工作过程

1 Activity/Fragment 生命周期事件如何通知LifecycleRegistry?
Activity/Fragment中持有LifecycleRegistry对象,那么是如何进行通讯的呢?
2 LifecycleRegistry 如何通知LifecycleObserver?
LifecycleRegistry对象又是 如何把这些事件通知给LifecycleObserver观察者的呢?
3 LifecycleObserver如何处理这些事件?
这个本篇博文暂时不讨论。

4 Lifecycles 解析

1 Activity/Fragment 生命周期事件如何通知LifecycleRegistry?
在Fragment中声明周期在回调的时候,都会调用LifecycleRegistry的handleLifecycleEvent(@NonNull Lifecycle.Event event)来进行与LifecycleRegistry的交互,如下:

void performCreate(Bundle savedInstanceState) {
        ...
        onCreate(savedInstanceState);
        ....
        mLifecycleRegistry.handleLifecycleEvent(Lifecycle.Event.ON_CREATE);
    }

    void performStart() {
        ....
        onStart();
        ....
        mLifecycleRegistry.handleLifecycleEvent(Lifecycle.Event.ON_START);
    }

    void performResume() {
        ....
        onResume();
        ....
        mLifecycleRegistry.handleLifecycleEvent(Lifecycle.Event.ON_RESUME);
    }

    void performPause() {
        mLifecycleRegistry.handleLifecycleEvent(Lifecycle.Event.ON_PAUSE);
        ....
        onPause();
        ....
    }

    void performStop() {
        mLifecycleRegistry.handleLifecycleEvent(Lifecycle.Event.ON_STOP);
        ....
        onStop();
        ....
    }

    void performDestroy() {
        mLifecycleRegistry.handleLifecycleEvent(Lifecycle.Event.ON_DESTROY);
        ....
        onDestroy();
        ....
    }

这里需要注意的是performCreate()、performStart()、performResume()会先调用自身的onXXX()方法,然后再调用LifecycleRegistry的handleLifecycleEvent()方法;而在performPause()、performStop()、performDestroy()中会先LifecycleRegistry的handleLifecycleEvent()方法 ,然后调用自身的onXXX()方法。借用一下别人的图,如下:

android 如何查看 architecture android architecture components_Android架构_03

这样,Fragment的生命周期状态就被传递到了LifecycleRegistry中,Activity中也应该类似

2 LifecycleRegistry 如何通知LifecycleObserver?
LifecycleRegistry中处理生命周期的核心方法如下:

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

这里逻辑比较简单,就不做说明了。接着调用moveToState(next)更新到下一个状态

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

主要做了两件事,第一就是将mState 置位为相应的状态,调用sync()同步

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

这里首先判断了mLifecycleOwner是否为null,如果为null说明不需要进行下面的分发了。接着如果没有同步过就进行状态的同步,主要根据之前添加的观察者的mObserverMap来进行状态同步。mObserverMap定义如下:

private FastSafeIterableMap<LifecycleObserver, ObserverWithState> mObserverMap =
            new FastSafeIterableMap<>();

最终经过一系列的判断和逻辑,这里以forwardPass为例:

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);
                observer.dispatchEvent(lifecycleOwner, upEvent(observer.mState));
                popParentState();
            }
        }
    }

会调用ObserverWithState的dispatchEvent(LifecycleOwner owner, Event event)方法

static class ObserverWithState {
        State mState;
        GenericLifecycleObserver mLifecycleObserver;

        ObserverWithState(LifecycleObserver observer, State initialState) {
            mLifecycleObserver = Lifecycling.getCallback(observer);
            mState = initialState;
        }

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

最终会调用到GenericLifecycleObserver #onStateChanged(LifecycleOwner source, Lifecycle.Event event);
这样就把Activity/Fragment的状态通知了LifecycleObserver,实现了观察者感知Activity/Fragment的生命周期

分析到这里,Lifecycles组件分析的也差不多了,Lifecycles如何添加观察者,以及LifecycleObserver如何处理具体事件,下一篇博客再进行分析。

参考:
https://shymanzhu.com/
https://developer.android.google.cn/topic/libraries/architecture/lifecycle.html
https://developer.android.google.cn/topic/libraries/architecture/lifecycle.html