您现在的位置是:首页 >学无止境 >Android JetPack组件之Lifecycle网站首页学无止境

Android JetPack组件之Lifecycle

Mr YiRan 2023-06-21 04:00:02
简介Android JetPack组件之Lifecycle

官方文档地址:https://developer.android.google.cn/topic/libraries/architecture/lifecycle

定义

Lifecycle是Jetpack提供的一个组件,可以感知Activity,Fragment的生命周期变化。这些组件可以根据 Activity 或 Fragment 的当前生命周期状态自动调整其行为。

相关概念

LifecycleOwner:我们的 Activity/Fragment 都实现了该接口,用以声明它是一个能够提供生命周期事件的宿主。同时必须复写getLifecycle()方法提供一个Lifecycle对象;

Lifecycle:是一个抽象类,里面定义了枚举State宿主的状态,Event 需要分发的事件的类型;

LifecycleRegistry: 是 Lifecycle 的唯一实现类,主要用来负责注册 Observer,以及分发宿主状态事件给它们。

基本使用

   //添加以下两个依赖	
    implementation "androidx.lifecycle:lifecycle-runtime-ktx:$lifecycle_version"
    implementation "androidx.lifecycle:lifecycle-common-java8:$lifecycle_version"

通过LifecycleOwner来获取到Lifecycler,View层已经实现了LifecyclerOnwer接口。比如说AppCompatActivity、Fragment已经实现了LifecycleOwner接口。

在activity中,或者fragment中

直接

this.lifecycle

kotlin的写法,如果是java get即可。

拿到以后,往里面添加监听

  this.lifecycle.addObserver()

一般来说,传接口都是要实现xxx接口的

这个是我们addObserver的方法

void addObserver(@NonNull LifecycleObserver observer)

也就是说,你需要传一个实现了LifecycleObserver 的类,或者实现了LifecycleObserver的子类才可以。

比如说我们的Presenter需要知道View层的生命周期变化。

我们把Owner传给Presneter

MusicPresenter(owner: LifecycleOwner)
初始化的时候,添加观察者

init {
    owner.lifecycle.addObserver(viewLifeImpl)
}

这个观察者的实现类

private val viewLifeImpl by lazy {
    ViewLifeImpl()
}

LifecycleEventObserver实现类,LifecycleEventObserver是LifecycleObserver的子类

inner class ViewLifeImpl : LifecycleEventObserver {

        /**
         * 被动通知View层的生命周期变化
         */
        override fun onStateChanged(source: LifecycleOwner, event: Lifecycle.Event) {
            when (event) {
                Lifecycle.Event.ON_START -> {
                    //监听GPS信号变化
                    println("监听GPS信号变化")
                    //开始监听网络变化
                }

                Lifecycle.Event.ON_PAUSE -> {
                    //停止GPS信号变化监听
                    println("停止GPS信号变化监听")
                    //停止网络状态变化更新
                }

                else -> {

                }
            }
        }

    }

当View层的生命周期发生变化的时候,就会通知到我们添加的监听了。

也就是会通知到onStateChange里头。

另外一种方式则是通过注解的方式。

同样也是实现LifecycleObserver接口

里面的方法添加注解,比如说:

inner class ValueObserverWrapper(private val valueObserver: (T?) -> Unit) :
        LifecycleObserver {

        @OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
        fun removeValueObserver() {
            println("removeValueObserver...")
            //当监听到当前的View,生命周期为Destroy的时候,就把LifecycleProvider从集合中删除
            viewLifecycleProviders.remove(valueObserver)
        }

        @OnLifecycleEvent(Lifecycle.Event.ON_STOP)
        fun onStop() {

        }

        @OnLifecycleEvent(Lifecycle.Event.ON_ANY)
        fun onAny() {

        }
    }

然后创建这个类,添加到Lifecycle里

以上两种方式,是被动的通知。也就是生命周期发生变化的时候,会通知你View层的生命周期发生变化了。

其实除了被动通知以外,还可以主动获取。

我们拿到Lifecycle以后,直接获取currentState,就知道当前View是一个什么状态了。

lifecycle.currentState

如果是java的话,就get

源码分析:

  • View层生命周期变化如何通知Lifecycle
  • Lifecycler如何通知观察者View层生命周期变化

View层生命周期变化如何通知Lifecycle?
首先在View层中(比如FragmentActivity)创建一个

final LifecycleRegistry mFragmentLifecycleRegistry = new LifecycleRegistry(this);

在View走onCreate方法的时候

mFragmentLifecycleRegistry.handleLifecycleEvent(Lifecycle.Event.ON_CREATE);

比如说Destroy的时候

 @Override
    protected void onDestroy() {
        super.onDestroy();
        ...
        mFragmentLifecycleRegistry.handleLifecycleEvent(Lifecycle.Event.ON_DESTROY);
    }

到这里,就通知到了Lifecycle生命周期发生变化了。

Lifecycle如何通知观察者View层生命周期变化?
我们在注册观察者的时候开始向Lifecycle挂上关系的

owner.lifecycle.addObserver(viewLifeImpl)

下面是addObserver的方法

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

其中 mObserverMap.putIfAbsent方法会将观察者添加到集合中

ObserverWithState previous = mObserverMap.putIfAbsent(observer, statefulObserver);

接着,我们回去看生命周期发生变化的地方

   public void handleLifecycleEvent(@NonNull Lifecycle.Event event) {
        State next = getStateAfter(event);
        moveToState(next);
    }

这是moveToState方法

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

这里其实就是事件分发了

// happens only on the top of stack (never in reentrance),
    // so it doesn't have to take in account parents
    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) {
                backwardPass(lifecycleOwner);
            }
            Entry<LifecycleObserver, ObserverWithState> newest = mObserverMap.newest();
            if (!mNewEventOccurred && newest != null
                    && mState.compareTo(newest.getValue().mState) > 0) {
                forwardPass(lifecycleOwner);
            }
        }
        mNewEventOccurred = false;
    }

再到这里的遍历

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

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

里面有一个 observer.dispatchEvent(lifecycleOwner, event);方法

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

onStateChange()方法

 mLifecycleObserver.onStateChanged(owner, event);

走到这里,就会通知到我们的实现代码了,因为mLifecycleObserver就是我们传进来保存到mObserverMap集合里的实例。

   inner  class ViewLifeImpl:LifecycleEventObserver{

        /**
         * 被动通知View层的生命周期变化
         */
        override fun onStateChanged(source: LifecycleOwner, event: Lifecycle.Event) {
            when(event){
                Lifecycle.Event.ON_START->{
                    println("监听GPS信号变化")
                    //开始监听网络变化
                }
                Lifecycle.Event.ON_PAUSE->{
                    println("停止GPS的信号变化")
                    //停止网络状态信息变化更新
                }
            }
        }
    }
风语者!平时喜欢研究各种技术,目前在从事后端开发工作,热爱生活、热爱工作。