美文网首页学习之鸿蒙&Android
Andorid-JetPack-Lifecycle组件用法和源码

Andorid-JetPack-Lifecycle组件用法和源码

作者: 信仰年輕 | 来源:发表于2021-07-04 19:11 被阅读0次

    本文目标

    理解并掌握Lifecycle组件用法和原理

    1.什么是Lifecycle

    具备宿主生命周期感知能力的组件,它能持有组件(如Activity 和 Fragment)生命周期状态的信息,并且运行其他观察者监听宿主的状态

    2.Lifecycle怎么用

    首先需要在app里的gradle中引入

    apply plugin: 'com.android.application'
    apply plugin: 'kotlin-android'
    apply plugin: 'kotlin-android-extensions'
    apply plugin: 'kotlin-kapt'
    
    dependencies {
        def lifecycle_version = "2.2.0"
        // ViewModel
        implementation "androidx.lifecycle:lifecycle-viewmodel:$lifecycle_version"
        // LiveData
        implementation "androidx.lifecycle:lifecycle-livedata:$lifecycle_version"
        // Lifecycles only (without ViewModel or LiveData)
        implementation "androidx.lifecycle:lifecycle-runtime:$lifecycle_version"
        //扫描所有编辑了 OnLifecycleEvent 注解的类,并生成实现类(可选)
        kapt "androidx.lifecycle:lifecycle-compiler:$lifecycle_version"
    }
    

    一般情况下ViewModel,LiveData,Lifecycle都是混合使用,当然也可以只是引入Lifecycle

    2.1第一种用法LifecycleObserver

    该用法如果没有在gradle中引入 kapt "androidx.lifecycle:lifecycle-compiler:$lifecycle_version"
    则是采用的 注解+反射去实现的,否则就是扫描所有编辑了 OnLifecycleEvent 注解的类,并生成实现类
    第1步,自定义MyLifeObserver观察者,用注解声明每个方法观察宿主的声明周期状态

    /**
     * Author: 信仰年轻
     * Date: 2020-11-25 16:16
     * Email: hydznsqk@163.com
     * Des:lifecycle组件库的使用
     * 我们用这个观查者来盯好需要感知生命周期的对象
     */
    public class MyLifeObserver implements LifecycleObserver {
    
        @OnLifecycleEvent(Lifecycle.Event.ON_CREATE)
        void onCreateYd() {
            Log.i("yd", "onCreateYd");
        }
    
        @OnLifecycleEvent(Lifecycle.Event.ON_START)
        void onStartYd() {
            Log.i("yd", "onStartYd");
        }
    
        @OnLifecycleEvent(Lifecycle.Event.ON_RESUME)
        void onResumeYd() {
            Log.i("yd", "onResumeYd");
        }
    
        @OnLifecycleEvent(Lifecycle.Event.ON_PAUSE)
        void onPauseYd() {
            Log.i("yd", "onPauseYd");
        }
    
        @OnLifecycleEvent(Lifecycle.Event.ON_STOP)
        void onStopYd() {
            Log.i("yd", "onStopYd");
        }
    
        @OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
        void onDestroyYd() {
            Log.i("yd", "onDestroyYd");
        }
    }
    

    第2步,在宿主中注册观察者,观察宿主生命周期状态变化,而且也不用实现反注册

    public class MainActivity extends AppCompatActivity {
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
           //注册观察者,监听Activity的生命周期
           getLifecycle().addObserver(new MyLifeObserver());
        }
    }
    

    这就可以完全监听MainActivity的生命周期了

    2.2第二种用法 LifecycleEventObserver

    该用法不会用到反射+注解的实现(建议使用这种)
    第1步,自定义MyLifecycleEventObserver观察者实现LifecycleEventObserver接口,重写onStateChanged()方法,方法内根据event自行判断

    /**
     * Author: 信仰年轻
     * Date: 2020-11-25 16:16
     * Email: hydznsqk@163.com
     * Des:lifecycle组件库的使用 第2种用法
     * 我们用这个观查者来盯好需要感知生命周期的对象
     */
    public class MyLifecycleEventObserver implements LifecycleEventObserver {
    
        @Override
        public void onStateChanged(@NonNull LifecycleOwner source, @NonNull Lifecycle.Event event) {
            //需要自行判断 life-event 是 onstart,还是onstop
            switch (event){
                case ON_CREATE:
                    Log.i("yd","ON_CREATE");
                    break;
                case ON_START:
                    Log.i("yd","ON_START");
                    break;
                case ON_RESUME:
                    Log.i("yd","ON_RESUME");
                    break;
                case ON_PAUSE:
                    Log.i("yd","ON_PAUSE");
                    break;
                case ON_STOP:
                    Log.i("yd","ON_STOP");
                    break;
                case ON_DESTROY:
                    Log.i("yd","ON_DESTROY");
                    break;
                default:
                    break;
            }
        }
    }
    

    第2步,在宿主中注册观察者,观察宿主生命周期状态变化,而且也不用实现反注册

    public class MainActivity extends AppCompatActivity {
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
           //注册观察者,监听Activity的生命周期
           getLifecycle().addObserver(new MyLifecycleEventObserver());
        }
    }
    

    这就可以完全监听MainActivity的生命周期了

    2.3第三种用法 FullLifecycleObserver

    但是目前在2.2.0这个版本,FullLifecycleObserver该接口 不是public的了

    interface FullLifecycleObserver extends LifecycleObserver {
    
        void onCreate(LifecycleOwner owner);
    
        void onStart(LifecycleOwner owner);
    
        void onResume(LifecycleOwner owner);
    
        void onPause(LifecycleOwner owner);
    
        void onStop(LifecycleOwner owner);
    
        void onDestroy(LifecycleOwner owner);
    }
    

    实现该接口也是可以去监听生命周期的,但是目前该接口并不public,所以还是用前面两种吧

    3.源码分析

    我们从MainActivity中注册观察者这行代码开始分析
    getLifecycle().addObserver(new MyLifecycleEventObserver());
    通过一顿找,getLifecycle()这行代码是在MainActivity的顶层父类ComponentActivity中,
    可以到在onCreate()方法中有一行ReportFragment.injectIfNeededIn(this),该行代码就是往Activity上添加一个fragment,用以报告生命周期的变化,
    然后LifecycleRegistry对象是成员变量直接就创建出来了

    public class ComponentActivity implements LifecycleOwner{
        private final LifecycleRegistry mLifecycleRegistry = new LifecycleRegistry(this);
    
        @Override
        protected void onCreate(@Nullable Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            //往Activity上添加一个fragment,用以报告生命周期的变化
            //目的是为了兼顾不是继承自AppCompactActivity的场景
            ReportFragment.injectIfNeededIn(this);
        }
    
        @NonNull
        @Override
        public Lifecycle getLifecycle() {
            return mLifecycleRegistry;
        }
    }
    

    来我们看下ReportFragment

    @RestrictTo(RestrictTo.Scope.LIBRARY_GROUP_PREFIX)
    public class ReportFragment extends Fragment {
    
        public static void injectIfNeededIn(Activity activity) {
            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 onStart() {
            super.onStart();
            dispatch(Lifecycle.Event.ON_START);
        }
    
        @Override
        public void onResume() {
            super.onResume();
            dispatch(Lifecycle.Event.ON_RESUME);
        }
    
        @Override
        public void onPause() {
            super.onPause();
            dispatch(Lifecycle.Event.ON_PAUSE);
        }
    
        @Override
        public void onStop() {
            super.onStop();
            dispatch(Lifecycle.Event.ON_STOP);
        }
    
        @Override
        public void onDestroy() {
            super.onDestroy();
            dispatch(Lifecycle.Event.ON_DESTROY);
        }
    
        private void dispatch(Lifecycle.Event event) {
            Activity activity = getActivity();
            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);
                }
            }
        }
    }
    
    

    可以看到生命周期事件发送是通过LifecycleRegistryandleLifecycleEvent(event);执行的,来我们继续看addObserver(new MyLifecycleEventObserver());这行代码,是在LifecycleRegistry类中

    4.LifecycleRegistry

    addObserver方法

    public class LifecycleRegistry extends Lifecycle {
    
        @Override
        public void addObserver(@NonNull LifecycleObserver observer) {
            //只要不是在宿主的DESTROYED状态注册的,这里都是INITIALIZED状态
            State initialState = mState == DESTROYED ? DESTROYED : INITIALIZED;
            //包装成拥有宿主状态的观察者
            ObserverWithState statefulObserver = new ObserverWithState(observer, initialState);
            //添加到mObserverMap这个map中
            ObserverWithState previous = mObserverMap.putIfAbsent(observer, statefulObserver);
    
            //1.先通过`calculateTargetState()`方法计算出来宿主应该到达的状态,实际上就是当前宿主的状态
            State targetState = calculateTargetState(observer);
            mAddingObserverCounter++;
           //2.把观察者的状态和targetState的状态做一个比较,如果 小于0,则说明观察者的状态还没有到达宿主的状态,既然没有,就让宿主的生命周期前进
            while ((statefulObserver.mState.compareTo(targetState) < 0
                    && mObserverMap.contains(observer))) {
                pushParentState(statefulObserver.mState);
                //3.分发事件,里面会upEvent
                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--;
        }
    
        //根据宿主状态来判断生命周期该接受哪个事件
        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);
        }
    
        static class ObserverWithState {
            State mState;
            LifecycleEventObserver mLifecycleObserver;
    
            ObserverWithState(LifecycleObserver observer, State initialState) {
                mLifecycleObserver = Lifecycling.lifecycleEventObserver(observer);
                mState = initialState;
            }
    
            void dispatchEvent(LifecycleOwner owner, Event event) {
                //根据event反推出新的宿主状态
                State newState = getStateAfter(event);
                mState = min(mState, newState);
                mLifecycleObserver.onStateChanged(owner, event);
                mState = newState;
            }
        }
    
        //根据event反推出新的宿主状态
        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);
        }
    }
    

    addObserver方法中

    • 1.先通过calculateTargetState()方法计算出来宿主应该到达的状态,实际上就是当前宿主的状态
    • 2.把观察者的状态和targetState的状态做一个比较,如果 小于0,则说明观察者的状态还没有到达宿主的状态,既然没有,就让宿主的生命周期前进
    • 3.根据宿主状态来判断生命周期该接受哪个事件
    • 4.接受完事件来到dispatchEvent方法中去分发事件
    • 5.分发完之后还会再次比较 statefulObserver.mState.compareTo(targetState) < 0 直到不小于0(观察者的状态和宿主的状态到达一致)

    while循环的目的是为了让ObserverWithState这个观察者状态从INITIALIZED状态前进到宿主当前的状态(可能是CREATED,STARTED,也可能是RESUMED)
    假设现在在宿主的onResume()方法中去注册一个观察者,我们的观察者会接受到哪几个生命周期的事件呢?
    首先会有onResume(),还会有onCreate(),onStart()等事件,这个逻辑就在这个while循环里面

    5.宿主生命周期与宿主状态模型图


    宿主的状态和生命周期不是一个概念,

    • 宿主在创建之初是INITIALIZED状态,当执行了ON_CREATE方法之后就会前进到CREATED状态,
    • 接着当宿主执行了ON_START方法就会前进到STARTED状态,
    • 然后执行了ON_RESUME方法就会前进到RESUMED状态,
      以上是生命周期前进的过程,从INITIALIZED初始化到RESUMED
      接着是生命周期倒退的过程
    • RESUMED状态执行了ON_PAUSE方法就会倒退到STARTED状态
    • 在之后宿主执行了ON_STOP方法倒退到CREATED状态
    • 执行了ON_DESTROY方法倒退到DESTROYED状态
       public enum State {
            DESTROYED,
            INITIALIZED,
            CREATED,
            STARTED,
            RESUMED;
        }
    

    6. 宿主的生命周期变化之后是如何分发给观察者的

    Fragment中会在每个生命周期的方法中调用 mLifecycleRegistry.handleLifecycleEvent(EVENT),如下代码

    public class Fragment implements  LifecycleOwner{
       LifecycleRegistry mLifecycleRegistry;
    
        private void initLifecycle() {
            mLifecycleRegistry = new LifecycleRegistry(this);
            mSavedStateRegistryController = SavedStateRegistryController.create(this);
        }
    
        @Override
        @NonNull
        public Lifecycle getLifecycle() {
            return mLifecycleRegistry;
        }
    
        void performCreate(Bundle savedInstanceState) {
            mLifecycleRegistry.handleLifecycleEvent(Lifecycle.Event.ON_CREATE);
        }
    
        void performStart() {
          mLifecycleRegistry.handleLifecycleEvent(Lifecycle.Event.ON_START);
        }
        ......
        void performResume() {
          mLifecycleRegistry.handleLifecycleEvent(Lifecycle.Event.ON_RESUME);
        }
    }
    

    来看下handleLifecycleEvent方法的具体实现

    public class LifecycleRegistry extends Lifecycle {
    
        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.");
            }
            
            //判断的是往这个集合中注册的Observer的所有的观察者状态都已经同步到了跟宿主一致的状态
            //如果还没有就进
            while (!isSynced()) {
                mNewEventOccurred = false;
    
                //宿主当前的状态和集合中每个观察者的状态做比较
                //如果宿主的状态 < 观察者的状态(发生在生命周期倒退的阶段)
                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 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();
                }
            }
        }
        //集合中所有观察者的状态前进到和宿主一样的状态,并且分发相应的事件
        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();
                }
            }
        }
    
        static class ObserverWithState {
            State mState;
            LifecycleEventObserver mLifecycleObserver;
    
            ObserverWithState(LifecycleObserver observer, State initialState) {
                mLifecycleObserver = Lifecycling.lifecycleEventObserver(observer);
                mState = initialState;
            }
    
            void dispatchEvent(LifecycleOwner owner, Event event) {
                State newState = getStateAfter(event);
                mState = min(mState, newState);
                mLifecycleObserver.onStateChanged(owner, event);
                mState = newState;
            }
        }
    }
    

    总结一下,宿主的生命周期和宿主的状态的关系,每个生命周期变化的时候都会分发相应的事件,并且会根据这个事件推导出宿主的状态,然后遍历所有的观察者,让他们的状态也随之升级或者降级,并且把本次事件分发给观察者

    7.LifecycleOwner,Lifecycle,LifecycleRegistry的关系

    • 1.LifecycleOwner,宿主的意思,代表这ActivityFragment,只要是实现该接口就必须要重写接口中的Lifecycle getLifecycle();方法,返回Lifecycle对象,其实该对象就是LifecycleRegistry对象
    • 2.Lifecycle,是个抽象类
    • 3.LifecycleRegistry 继承自 Lifecycle
    public interface LifecycleOwner {
        /**
         * Returns the Lifecycle of the provider.
         *
         * @return The lifecycle of the provider.
         */
        @NonNull
        Lifecycle getLifecycle();
    }
    

    相关文章

      网友评论

        本文标题:Andorid-JetPack-Lifecycle组件用法和源码

        本文链接:https://www.haomeiwen.com/subject/rgxiultx.html