其他分享
首页 > 其他分享> > JetPack组件--LifeCycle生命周期组件详解

JetPack组件--LifeCycle生命周期组件详解

作者:互联网

LifeCycle简介

LifeCycle组件主要用于对具有生命周期对象(如Activity和Fragment)进行生命分发,使得其他对象能够其生命周期的变化。

它是JetPack其他组件的基础,如JetPack中的LiveData就用到了该组件,实现了Activity在后台时不回调事件,在Activity销毁时自动取消对Activity解除观察的功能

为什么要进行生命分发

我们使用具备Android生命周期组件时经常可能遇到以下场景

1,需要在Activity的onCreate()方法通知成员变量进行初始化(如MVP中的presenter,AudioManager等)

2,需要在Activity的onStop(),onDestroy()方法通知成员变量进行解绑释放资源,防止内存泄漏等

LifeCycle出现前的混沌岁月

1,在Activity/Fragment中手动回调观察者生命周期事件

在LifeCycle组件出现前,我们遇到这种场景有两种方式,一种就是手动在Activity的各个生命周期中手动回调成员变量相应的方法,代码如下:

MyPresenter {

    fun start(){
       //doSomething
    }

    fun stop(){
      //doSomething
    }
}

class MainActivity : AppCompatActivity() {
    private val mPresenter = MyPresenter()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        mPresenter.start()
    }

    override fun onDestroy() {
        super.onDestroy()
        mPresenter.stop()
    }
}

这种写法虽然能满足我们自己页面分发生命周期的需求,但需要手动调用,就往往可能出现忘记调用,导致bug出现。

而且当Activity是第三方页面,就无法使用这种方式进行生命周期进行分发了。

2,Application.ActivityLifecycleCallbacks

在LifeCycle出现之前,Android系统提供了Application.ActivityLifecycleCallbacks这样接口让我们能够感知应用内所有的Activity生命周期的变化,具体用法如下:

class MyPresenter: Application.ActivityLifecycleCallbacks {

    /**
     * Called when the Activity calls [super.onCreate()][Activity.onCreate].
     */
    override fun onActivityCreated(activity: Activity, savedInstanceState: Bundle?) {
        // dosomething
    }

    /**
     * Called when the Activity calls [super.onDestroy()][Activity.onDestroy].
     */
    override fun onActivityDestroyed(activity: Activity) {
        // dosomething
    }

    /**
     * Called when the Activity calls [super.onPause()][Activity.onPause].
     */
    override fun onActivityPaused(activity: Activity) {

    }

    /**
     * Called when the Activity calls [super.onStart()][Activity.onStart].
     */
    override fun onActivityStarted(activity: Activity) {

    }

    /**
     * Called when the Activity calls
     * [super.onSaveInstanceState()][Activity.onSaveInstanceState].
     */
    override fun onActivitySaveInstanceState(activity: Activity, outState: Bundle) {

    }

    /**
     * Called when the Activity calls [super.onStop()][Activity.onStop].
     */
    override fun onActivityStopped(activity: Activity) {

    }

    /**
     * Called when the Activity calls [super.onResume()][Activity.onResume].
     */
    override fun onActivityResumed(activity: Activity) {

    }

}

class MainActivity : AppCompatActivity() {
    private val mPresenter = MyPresenter()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        //注意这是application的方法
        application.registerActivityLifecycleCallbacks(mPresenter)
        // api大于等于29支持直接通过activity注册生命回调的方法
       // registerActivityLifecycleCallbacks(mPresenter)

    }

    override fun onDestroy() {
        super.onDestroy()
        //不需要使用,需要解除注册
        application.unregisterActivityLifecycleCallbacks(mPresenter)
    }
}

采用这种方式注册后,我们就能在Activity生命周期变化的时候收到回调,从而执行相应的逻辑。因为是同步回调,所以我们要注意不能在回调方法中执行耗时操作,防止出现卡顿。

因为是注册在Application上的,mPresenter对象可以监听到Application的所有Activity的生命周期回调。

而在sdk>=29版本上,Activity也提供了自身的registerActivityLifecycleCallbacks方法,调用Activity这个方法注册的观察者将只会收到注册的Activity生命周期事件的回调。

Application.ActivityLifecycleCallbacks的优点:

通过定义Application.ActivityLifecycleCallbacks接口屏蔽了不同观察者的差异。同时在Activity的各个生命回调方法中分发事件,从根本保障了各个观察者都能在生命周期变化时接收到事件。比较通用,既能用于监听我们自身的Activity生命事件,也能监听第三方Activity事件。

Application.ActivityLifecycleCallbacks缺点:

有了Application.ActivityLifecycleCallbacks,解决了Activity生命周期分发的问题,但它仅适用于Activity的生命周期分发,而Android具有生命周期的对象也不止有Activity(例如Service,Fragment)等。

所以谷歌推出了我们今天的主角 --JetPack之LifeCycle生命周期组件

LifeCycle组件常见类简介

LifecycleRegistry主要源码解析

LifeCycleRegister是LifeCycle的实现类,实现了添加移除LifeCycleObserver的逻辑和生命周期状态管理,并且能够在LifeCycleOwner的生命周期发生变化时及时通知LifeCycleObserver。 有了LifeCycleRegister类,大大简化开发者使用LifeCyclerOwner的成本。使得Activity,Fragment不需要直接和LifeCycleObserver打交道。只需要在生命周期变化时调用LifeCycleRegister的handleLifecycleEvent(@NonNull Lifecycle.Event event) 方法即可。

下面先看它的构造方法:

 public LifecycleRegistry(@NonNull LifecycleOwner provider) {
        //持有的是LifeCycleOwner对象的弱引用,防止因为LifeCycleRegistery被长生命周期对象持有而         
        //造成LifeCycleOwner内存泄漏
        mLifecycleOwner = new WeakReference<>(provider);
        mState = INITIALIZED;
    }

构造方法很简单,只是保存了传入来的LifeCycleOwner对象并且将当前状态置为INITIALIZED

接下来看一下它添加观察者的方法

    @Override
    public void addObserver(@NonNull LifecycleObserver observer) {
        State initialState = mState == DESTROYED ? DESTROYED : INITIALIZED;
        //将LifecycleObserver和它的状态封装成ObserverWithState对象
        ObserverWithState statefulObserver = new ObserverWithState(observer, initialState);

        ObserverWithState previous = mObserverMap.putIfAbsent(observer, statefulObserver);
        //表示statefulObserver已经添加过了,故直接返回
        if (previous != null) {
            return;
        }
        LifecycleOwner lifecycleOwner = mLifecycleOwner.get();
        //lifecycleOwner为null,表示LifecycleOwner已被回收,故不需要观察了,返回
        if (lifecycleOwner == null) {
            // it is null we should be destroyed. Fallback quickly
            return;
        }

        boolean isReentrance = mAddingObserverCounter != 0 || mHandlingEvent;
        //计算出新加入的observer需要转变到的目标状态
        State targetState = calculateTargetState(observer);
        mAddingObserverCounter++;
        //当observer的mState小于目标状态时且observer没有被移除时,向observer分发生命周期事件
        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);
        }
        //为false,代表当前没有在sync()以及没有同时并发添加Observer
        //主要为了防止重复调用sync()方法
        if (!isReentrance) {
            // we do sync only on the top level.
            //同步所有观察者状态,使它们保持一致
            sync();
        }
        mAddingObserverCounter--;
    }

   //返回当前状态的下一个状态
   private static Event upEvent(State state) {
        switch (state) {
            case INITIALIZED:
            case DESTROYED:
                return ON_CREATE;
            case CREATED:
                return ON_START;
            case STARTED:
                return ON_RESUME;
            case RESUMED:
                throw new IllegalArgumentException();
        }
        throw new IllegalArgumentException("Unexpected state value " + state);
    }

从上面的代码分析可以看出当我们在onResume方法中添加Observer,Observer将会连续收到ON_CREATE,ON_START,ON_RESUME事件的回调。

下面看下它分发事件的方法

    public void handleLifecycleEvent(@NonNull Lifecycle.Event event) {
        //根据event获取对应的state
        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;
        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) {
            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;
    }

在backwardPass(lifecycleOwner)和forwardPass(lifecycleOwner)方法调用了ObserverWithState的 dispatchEvent(LifecycleOwner owner, Event event) 方法

 void dispatchEvent(LifecycleOwner owner, Event event) {
            State newState = getStateAfter(event);
            mState = min(mState, newState);
            //把事件通知LifeCycleObsever
            mLifecycleObserver.onStateChanged(owner, event);
            mState = newState;
        }

至此LifeCycleRegister接收事件并把它分发给LifeCycleObserver的流程已经分析完了。

LifeCycle用到的一些设计思想和设计模式

从前面可知,LifeCycleObserver只是一个空接口。它的子接口有LifecycleEventObserverFullLifecycleObserver,甚至还可以采用注解的方式来声明生命周期回调函数。 那ObserverWithState是如何兼容不同类型的LifeCycleObserver呢?

  static class ObserverWithState {
        State mState;
        LifecycleEventObserver mLifecycleObserver;

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

        //省略...
 }

借用业志陈的从源码看 Jetpack(1)-Lifecycle 源码详解的一段结论

ObserverWithState 将外界传入的 LifecycleObserver 对象传给 Lifecycling 进行类型包装,将反射逻辑和接口回调逻辑都给汇总综合成一个新的 LifecycleEventObserver 对象,从而使得 Event 分发过程都统一为一个入口。

ObserverWithState将复杂的反射逻辑和接口回调处理和类型包装封装到LifeCycling类中,将生成新的 LifecycleEventObserver 对象的过程和LifeCycleRegistry解耦,体现了单一职责。使得LifeCycleRegistry仅需通过onStateChanged 方法就能完成生命周期事件的分发。

 static LifecycleEventObserver lifecycleEventObserver(Object object) {
        boolean isLifecycleEventObserver = object instanceof LifecycleEventObserver;
        boolean isFullLifecycleObserver = object instanceof FullLifecycleObserver;
        //实现了LifecycleEventObserver接口和FullLifecycleObserver接口
        if (isLifecycleEventObserver && isFullLifecycleObserver) {
            return new FullLifecycleObserverAdapter((FullLifecycleObserver) object,
                    (LifecycleEventObserver) object);
        }
        //只实现了FullLifecycleObserver接口
        if (isFullLifecycleObserver) {
            return new FullLifecycleObserverAdapter((FullLifecycleObserver) object, null);
        }
        //只实现了LifecycleEventObserver接口
        if (isLifecycleEventObserver) {
            return (LifecycleEventObserver) object;
        }

        // 省略...
    }

    class FullLifecycleObserverAdapter implements LifecycleEventObserver {

    private final FullLifecycleObserver mFullLifecycleObserver;
    private final LifecycleEventObserver mLifecycleEventObserver;

    FullLifecycleObserverAdapter(FullLifecycleObserver fullLifecycleObserver,
            LifecycleEventObserver lifecycleEventObserver) {
        mFullLifecycleObserver = fullLifecycleObserver;
        mLifecycleEventObserver = lifecycleEventObserver;
    }

    @Override
    public void onStateChanged(@NonNull LifecycleOwner source, @NonNull Lifecycle.Event event) {
        switch (event) {
            case ON_CREATE:
                mFullLifecycleObserver.onCreate(source);
                break;
            case ON_START:
                mFullLifecycleObserver.onStart(source);
                break;
            case ON_RESUME:
                mFullLifecycleObserver.onResume(source);
                break;
            case ON_PAUSE:
                mFullLifecycleObserver.onPause(source);
                break;
            case ON_STOP:
                mFullLifecycleObserver.onStop(source);
                break;
            case ON_DESTROY:
                mFullLifecycleObserver.onDestroy(source);
                break;
            case ON_ANY:
                throw new IllegalArgumentException("ON_ANY must not been send by anybody");
        }
        if (mLifecycleEventObserver != null) {
            mLifecycleEventObserver.onStateChanged(source, event);
        }
    }

FullLifecycleObserverAdapter这个类采用了适配器模式,适配了FullLifecycleObserverLifecycleEventObserver这两个接口。它自身实现了LifeCycleEventObserver接口,当onStateChanged 时,它会回调分别回调成员变量mFullLifecycleObservermLifecycleEventObserver的对应生命周期方法。

适配器模式,英文翻译为Adapter Design Pattern。这个模式是用来做适配的,它将不兼容的接口转换为可兼容的接口,让原本由于接口不兼容而不能一起工作的类可以一起工作。

而之所以要用到适配器模式是因为LifecycleObserver的子接口基于接口隔离原则,没有设计大而全的子接口。这要好处在于接口的实现类和调用者,能不依赖它不需要的接口函数。

另外LifeCycle组件用到了基于接口而非实现编程的设计原则。例如LifeCycle持有的LifeCycleObserver都是接口,这使得用户可以根据业务定制相应LifeCycleObserver。这大大提高LifeCycle组件的扩展性和灵活性。

有关LifeCycling源码分析还有很多,但限于篇幅,而且这也不算LifeCycle的核心,故不往下分析了。大家有兴趣可以看下从源码看 Jetpack(1)-Lifecycle 源码详解

总结

LifeCycle的出现使得生命周期组件可以很方便地向观察者分发生命状态变化事件。相比ActivityLifecycleCallback,它更加抽象,解耦了生命周期组件和观察者组件的关系,使得生命周期组件不需要直接和观察者组件打交道,而是将状态分发给LifeCycle,再由LifeCycle统一分发给观察者组件,使得LifeCyclerOwner组件分发生命周期更加简易。除此之外,LifeCycleRegistry持有LifeCycleOwner的弱引用对象的方式可以减少内存泄漏的发生,提高了代码的健壮性。通过基于接口编程而实现编程提高了代码扩展性和灵活性。

最后

小编在网上收集了一些 Android 开发相关的学习文档、面试题、Android 核心笔记等等文档,希望能帮助到大家学习提升,如有需要参考的可以直接去我 GitHub地址:https://github.com/733gh/Android-T3 访问查阅。

标签:case,生命周期,--,JetPack,接口,Activity,组件,LifeCycle,mState
来源: https://blog.csdn.net/u012165769/article/details/117172581