Android Jetpack 之 Lifecycle

Lifecycle 是一个专门用来处理生命周期的库,它能够帮助我们将 Acitivity、Framgent 的生命周期处理与业务逻辑处理进行解耦,让我们能够更加专注于业务;

基于 Lifecycle 的特性,在任意生命周期方法内注册观察者都能接收到完整的生命周期事件,比如在onResume 中注册一个观察者它会依次收到:
LifecycleEvent.onCreate -> LifecycleEvent.onStart -> LifecycleEvent.onResume。

相关依赖库如下:

dependencies {
    def lifecycle_version = "2.3.0"
    def arch_version = "2.1.0"

    // ViewModel
    implementation "androidx.lifecycle:lifecycle-viewmodel-ktx:$lifecycle_version"
    // LiveData
    implementation "androidx.lifecycle:lifecycle-livedata-ktx:$lifecycle_version"
    // Lifecycles only (without ViewModel or LiveData)
    implementation "androidx.lifecycle:lifecycle-runtime-ktx:$lifecycle_version"

    // Saved state module for ViewModel
    implementation "androidx.lifecycle:lifecycle-viewmodel-savedstate:$lifecycle_version"

    // Jetpack Compose Integration for ViewModel
    implementation "androidx.lifecycle:lifecycle-viewmodel-compose:1.0.0-alpha01"

    // Annotation processor
    kapt "androidx.lifecycle:lifecycle-compiler:$lifecycle_version"
    // alternately - if using Java8, use the following instead of lifecycle-compiler
    implementation "androidx.lifecycle:lifecycle-common-java8:$lifecycle_version"

    // optional - helpers for implementing LifecycleOwner in a Service
    implementation "androidx.lifecycle:lifecycle-service:$lifecycle_version"

    // optional - ProcessLifecycleOwner provides a lifecycle for the whole application process
    implementation "androidx.lifecycle:lifecycle-process:$lifecycle_version"

    // optional - ReactiveStreams support for LiveData
    implementation "androidx.lifecycle:lifecycle-reactivestreams-ktx:$lifecycle_version"

    // optional - Test helpers for LiveData
    testImplementation "androidx.arch.core:core-testing:$arch_version"
}

相关类介绍:

  • Lifecycle 抽象类,用于管理 Observer,包括 Event 和 State 两个枚举类型。
  • LifecycleOwner 持有 Lifecycle 类的接口。如 AppCompatActivity 和 Fragment。
  • LifecycleObserver 生命周期观察者,直接实现类有 LifecycleEventObserverFullLifecycleObserver
  • LifecycleRegistry Lifecycle 的实现类。可以自定义 LifecycleOwner。

Lifecycle

/**
* Defines an object that has an Android Lifecycle.
*/
public abstract class Lifecycle {
    public abstract void addObserver(LifecycleObserver observer);
    public abstract void removeObserver(LifecycleObserver observer);
    public abstract State getCurrentState();

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

    public enum State {
        DESTROYED,
        INITIALIZED,
        CREATED,
        STARTED,
        RESUMED;
        public boolean isAtLeast(State state) {
            return compareTo(state) >= 0;
        }
    }
}

Lifecycle 是一个抽象类,其内部不仅包括了添加和移除观察者的方法,还包括 Event 和 State 枚举。State 指的是 Lifecycle 的生命周期所处的状态。Event 代表 Lifecycle 生命周期对应的事件,这些事件会映射到 Activity 和 Fragment 中的回调事件中。

Androi d Lifecycle State 和 Event 对应关系

LifecycleRegistry

public class LifecycleRegistry extends Lifecycle {

    public LifecycleRegistry(@NonNull LifecycleOwner provider) {
        this(provider, true);
    }

    private LifecycleRegistry(@NonNull LifecycleOwner provider, boolean enforceMainThread) {
        mLifecycleOwner = new WeakReference<>(provider);
        mState = INITIALIZED;
        mEnforceMainThread = enforceMainThread;
    }
}

LifecycleRegistry 是 Lifecycle 的实现类。必须在主线程。对目标对象是弱引用,不会导致 Activity 内存泄漏。

源码分析

ComponentActivity 和 Fragment 都实现了 LifecycleOwner 接口。

// androidx.activity:activity:1.2.0
public class ComponentActivity extends androidx.core.app.ComponentActivity
    implements LifecycleOwner,... {

    private final LifecycleRegistry mLifecycleRegistry = new LifecycleRegistry(this);

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

    @CallSuper
    @Override
    protected void onSaveInstanceState(@NonNull Bundle outState) {
        Lifecycle lifecycle = getLifecycle();
        if (lifecycle instanceof LifecycleRegistry) {
            ((LifecycleRegistry) lifecycle).setCurrentState(Lifecycle.State.CREATED);
        }
        super.onSaveInstanceState(outState);
    }
    
    @Override
    public Lifecycle getLifecycle() {
        return mLifecycleRegistry;
    }
}

Activity 的生命周期代理给 ReportFragment 分发。

public class ReportFragment extends Fragment {

    public static void injectIfNeededIn(Activity activity) {
        // >= 10.0 使用 Activity 生命周期回调的方式分发生命周期
        if (Build.VERSION.SDK_INT >= 29) {
            activity.registerActivityLifecycleCallbacks(
                    new LifecycleCallbacks());
        }
        
        // < 10.0 使用 Fragemnt 分发生命周期,以兼容以前的版本。
        android.app.FragmentManager manager = activity.getFragmentManager();
        if (manager.findFragmentByTag(REPORT_FRAGMENT_TAG) == null) {
            manager.beginTransaction().add(new ReportFragment(), REPORT_FRAGMENT_TAG).commit();
            manager.executePendingTransactions();
        }
    }

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

    private void dispatch(@NonNull Lifecycle.Event event) {
        if (Build.VERSION.SDK_INT < 29) {
            dispatch(getActivity(), event);
        }
    }

    static void dispatch(@NonNull Activity activity, @NonNull Lifecycle.Event event) {
        // LifecycleRegistryOwner 已废弃
        if (activity instanceof LifecycleRegistryOwner) {
            ((LifecycleRegistryOwner) activity).getLifecycle().handleLifecycleEvent(event);
            return;
        }

        if (activity instanceof LifecycleOwner) {
            Lifecycle lifecycle = ((LifecycleOwner) activity).getLifecycle();
            if (lifecycle instanceof LifecycleRegistry) {
                ((LifecycleRegistry) lifecycle).handleLifecycleEvent(event);
            }
        }
    }

    static class LifecycleCallbacks implements Application.ActivityLifecycleCallbacks {
        // onActivityPostXXX() 在生命周期方法之后调用
        @Override
        public void onActivityPostCreated(@NonNull Activity activity,
                @Nullable Bundle savedInstanceState) {
            dispatch(activity, Lifecycle.Event.ON_CREATE);
        }

        // onActivityPreXXX() 在生命周期方法之前调用
        @Override
        public void onActivityPrePaused(@NonNull Activity activity) {
            dispatch(activity, Lifecycle.Event.ON_PAUSE);
        }
    }
}

在 API 29 及以上直接使用 Activity#registerActivityLifecycleCallbacks 直接注册了生命周期回调,然后给当前 activity 添加一个无界面的 ReportFragment 代理生命周期回调。

// androidx.fragment:fragment:1.3.0
public class Fragment implements LifecycleOwner,...{
    LifecycleRegistry mLifecycleRegistry;

    public Fragment() {
        initLifecycle();
    }

    private void initLifecycle() {
        mLifecycleRegistry = new LifecycleRegistry(this);
    }

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

    // performStart() 和 performResume() 类似
    void performCreate(Bundle savedInstanceState) {
        onCreate(savedInstanceState);
        mLifecycleRegistry.handleLifecycleEvent(Lifecycle.Event.ON_CREATE);
    }

    // performStop() 和 performDestroy() 类似
    void performPause() {
        mLifecycleRegistry.handleLifecycleEvent(Lifecycle.Event.ON_PAUSE);
        onPause();
    }
}

观察者都是通过 LifecycleRegistry 类注册的,是 Lifecycle 的唯一实现类。

public class LifecycleRegistry extends Lifecycle {
    private FastSafeIterableMap<LifecycleObserver, ObserverWithState> mObserverMap =
            new FastSafeIterableMap<>();
    private final WeakReference<LifecycleOwner> mLifecycleOwner;
    private State mState;

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

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

    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;
            // no need to check eldest for nullability, because isSynced does it for us.
            if (mState.compareTo(mObserverMap.eldest().getValue().mState) < 0) {
                // 如 onPause -> onResume
                backwardPass(lifecycleOwner);
            }
            Map.Entry<LifecycleObserver, ObserverWithState> newest = mObserverMap.newest();
            if (!mNewEventOccurred && newest != null
                    && mState.compareTo(newest.getValue().mState) > 0) {
                // 如 onResume -> onPause
                forwardPass(lifecycleOwner);
            }
        }
        mNewEventOccurred = false;
    }

    private void backwardPass(LifecycleOwner lifecycleOwner) {
        Iterator<Map.Entry<LifecycleObserver, ObserverWithState>> descendingIterator =
                mObserverMap.descendingIterator();
        while (descendingIterator.hasNext() && !mNewEventOccurred) {
            Map.Entry<LifecycleObserver, ObserverWithState> entry = descendingIterator.next();
            ObserverWithState observer = entry.getValue();
            while ((observer.mState.compareTo(mState) > 0 && ...)) {
                Event event = Event.downFrom(observer.mState);
                observer.dispatchEvent(lifecycleOwner, event);
            }
        }
    }

    private void forwardPass(LifecycleOwner lifecycleOwner) {
        Iterator<Map.Entry<LifecycleObserver, ObserverWithState>> ascendingIterator =
                mObserverMap.iteratorWithAdditions();
        while (ascendingIterator.hasNext() && !mNewEventOccurred) {
            Map.Entry<LifecycleObserver, ObserverWithState> entry = ascendingIterator.next();
            ObserverWithState observer = entry.getValue();
            while ((observer.mState.compareTo(mState) < 0 && ...)) {
                final Event event = Event.upFrom(observer.mState);
                observer.dispatchEvent(lifecycleOwner, event);
            }
        }
    }

    @Override
    public void addObserver(@NonNull LifecycleObserver observer) {
        State initialState = mState == DESTROYED ? DESTROYED : INITIALIZED;
        // 包装观察者,绑定初始状态。同时反射获取被 OnLifecycleEvent 注解的方法
        ObserverWithState statefulObserver = new ObserverWithState(observer, initialState);
        // 保存观察者
        ObserverWithState previous = mObserverMap.putIfAbsent(observer, statefulObserver);
        // 已经添加过,返回
        if (previous != null) {
            return;
        }
        State targetState = calculateTargetState(observer);
        // 比较观察者的状态和目标对象状态,小于 0 说明两者状态还没有对齐
        // 观察者会收到多个生命周期事件
        while ((statefulObserver.mState.compareTo(targetState) < 0
                && mObserverMap.contains(observer))) {
            // 根据当前状态,获取到后一个状态的事件
            final Event event = Event.upFrom(statefulObserver.mState);
            statefulObserver.dispatchEvent(lifecycleOwner, event);
            // 重新计算观察者当前的状态,不一致会重新进入循环
            targetState = calculateTargetState(observer);
        }
    }

    static class ObserverWithState {
        State mState;
        LifecycleEventObserver mLifecycleObserver;

        ObserverWithState(LifecycleObserver observer, State initialState) {
            // 适配成 ReflectiveGenericLifecycleObserver 或 FullLifecycleObserverAdapter
            mLifecycleObserver = Lifecycling.lifecycleEventObserver(observer);
            mState = initialState;
        }

        void dispatchEvent(LifecycleOwner owner, Event event) {
            mLifecycleObserver.onStateChanged(owner, event);
        }
    }
}

ObserverWithState#mState 的作用是新的事件触发后 遍历通知所有观察者时,判断是否已经通知这个观察者了,即防止重复通知。

如果在目标对象 RESUMED 状态注册观察者,那么观察者会接收到三次生命周期事件:

  1. 第一次:分发 ON_CREATE 事件,观察者状态 INITIALIZED->CREATED
  2. 第二次:分发 ON_START 事件,观察者状态 CREATED->STARTED
  3. 第三次:分发 ON_RESUME 事件,观察者状态 STARTED->RESUMED
public class Lifecycling {
    static LifecycleEventObserver lifecycleEventObserver(Object object) {
        // 根据 Observer 类型,返回 FullLifecycleObserverAdapter 对象

        final Class<?> klass = object.getClass();
        int type = getObserverConstructorType(klass);
        if (type == GENERATED_CALLBACK) {
            // 一个构造方法返回 SingleGeneratedAdapterObserver 对象
            // 多于一个构造方法返回 CompositeGeneratedAdaptersObserver 对象
        }
        return new ReflectiveGenericLifecycleObserver(object);
    }
}
class ReflectiveGenericLifecycleObserver implements LifecycleEventObserver {
    private final Object mWrapped;
    private final CallbackInfo mInfo;

    ReflectiveGenericLifecycleObserver(Object wrapped) {
        mWrapped = wrapped;
        mInfo = ClassesInfoCache.sInstance.getInfo(mWrapped.getClass());
    }

    @Override
    public void onStateChanged(@NonNull LifecycleOwner source, @NonNull Event event) {
        mInfo.invokeCallbacks(source, event, mWrapped);
    }
}
final class ClassesInfoCache {
    private final Map<Class<?>, CallbackInfo> mCallbackMap = new HashMap<>();
    private final Map<Class<?>, Boolean> mHasLifecycleMethods = new HashMap<>();

    CallbackInfo getInfo(Class<?> klass) {
        CallbackInfo existing = mCallbackMap.get(klass);
        if (existing != null) {
            return existing;
        }
        existing = createInfo(klass, null);
        return existing;
    }

    private CallbackInfo createInfo(Class<?> klass, @Nullable Method[] declaredMethods) {
        Map<MethodReference, Lifecycle.Event> handlerToEvent = new HashMap<>();
        // 反射获取 Observer 类中的所有方法
        Method[] methods = declaredMethods != null ? declaredMethods : getDeclaredMethods(klass);
        boolean hasLifecycleMethods = false;
        for (Method method : methods) {
            OnLifecycleEvent annotation = method.getAnnotation(OnLifecycleEvent.class);
            // 检查方法是否被 OnLifecycleEvent 注解
            if (annotation == null) {
                continue;
            }
            hasLifecycleMethods = true;
            // 获取注解方法参数
            Class<?>[] params = method.getParameterTypes();
            int callType = CALL_TYPE_NO_ARG;
            // 如果有一个参数,参数列表必须是(LifecycleOwner)
            // 若果有两个参数,参数列表必须是(LifecycleOwner, Lifecycle.Event),而且必须是 Lifecycle.Event.ON_ANY 注解
            // 超过两个参数抛出异常
            MethodReference methodReference = new MethodReference(callType, method);
            // 保存到 handlerToEvent Map 中
            verifyAndPutHandler(handlerToEvent,; methodReference, event, klass);
        }
        CallbackInfo info = new CallbackInfo(handlerToEvent);
        // 保存 CallbackInfo
        mCallbackMap.put(klass, info);
        mHasLifecycleMethods.put(klass, hasLifecycleMethods);
        return info;
    }

    static class CallbackInfo {
        final Map<Lifecycle.Event, List<MethodReference>> mEventToHandlers;
        final Map<MethodReference, Lifecycle.Event> mHandlerToEvent;

        CallbackInfo(Map<MethodReference, Lifecycle.Event> handlerToEvent) {
            mHandlerToEvent = handlerToEvent;
            mEventToHandlers = new HashMap<>();
            // 遍历 handlerToEvent,保存在 mEventToHandlers 中
        }

        void invokeCallbacks(LifecycleOwner source, Lifecycle.Event event, Object target) {
            invokeMethodsForEvent(mEventToHandlers.get(event), source, event, target);
            invokeMethodsForEvent(mEventToHandlers.get(Lifecycle.Event.ON_ANY), source, event,
                    target);
        }

        private static void invokeMethodsForEvent(List<MethodReference> handlers,...) {
            for (int i = handlers.size() - 1; i >= 0; i--) {
                handlers.get(i).invokeCallback(source, event, mWrapped);
            }
        }
    }

    static final class MethodReference {
        void invokeCallback(LifecycleOwner source, Lifecycle.Event event, Object target) {
            switch (mCallType) {
                case CALL_TYPE_NO_ARG:
                    mMethod.invoke(target);
                    break;
                case CALL_TYPE_PROVIDER:
                    mMethod.invoke(target, source);
                    break;
                case CALL_TYPE_PROVIDER_WITH_EVENT:
                    mMethod.invoke(target, source, event);
                    break;
            }
        }
    }
}
时序图
Uml

总结

  1. Activity 或 Fragemnt 的生命周期是通过 ReportFragment 实现的。
  2. 注册观察者,通过反射收集观察者中被 OnLifecycleEvent 注解的方法,封装成 ObserverWithState 保存在 mObserverMap 中。
  3. 同步观察者状态。如果间隔多个状态,观察者会依次收到多个生命周期事件,直到状态一致。
  4. 收到事件时,从 mObserverMap 中获取观察者信息,通过反射回调观察者中的方法。

参考

[1]Lifecycle - developer
[2] Jetpack架构组件库-Lifecycle源码解析之知其所以然

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 206,968评论 6 482
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 88,601评论 2 382
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 153,220评论 0 344
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 55,416评论 1 279
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 64,425评论 5 374
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 49,144评论 1 285
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 38,432评论 3 401
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 37,088评论 0 261
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 43,586评论 1 300
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 36,028评论 2 325
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 38,137评论 1 334
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,783评论 4 324
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 39,343评论 3 307
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 30,333评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,559评论 1 262
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 45,595评论 2 355
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,901评论 2 345

推荐阅读更多精彩内容