美文网首页
Jetpack——Lifecyle使用和源码分析

Jetpack——Lifecyle使用和源码分析

作者: 刘孙猫咪 | 来源:发表于2021-04-23 08:51 被阅读0次

    在项目开发中,会涉及到像百度地图一样的sdk的使用,在使用百度定位的时候,在当前页面进行定位注册后,根据其文档需要在当前页面的onStart、onStop、onDestory等生命周期回调中进行定位的注册、注销等操作,如果重写当前页面的生命周期等方法,然后在生命周期中进行逻辑实现,会导致当前页面代码逻辑变的臃肿,并且基本没有解耦性;也可以自己写一个类,然后通过callback回调进行处理;

    class MyLocationListener {
        public MyLocationListener(Context context, Callback callback) {
            // ...
        }
    
        void start() {
            // connect to system location service
        }
    
        void stop() {
            // disconnect from system location service
        }
    }
    
    class MyActivity extends AppCompatActivity {
        private MyLocationListener myLocationListener;
    
        @Override
        public void onCreate(...) {
            myLocationListener = new MyLocationListener(this, (location) -> {
                // update UI
            });
        }
    
        @Override
        public void onStart() {
            super.onStart();
            myLocationListener.start();
            // manage other components that need to respond
            // to the activity lifecycle
        }
    
        @Override
        public void onStop() {
            super.onStop();
            myLocationListener.stop();
            // manage other components that need to respond
            // to the activity lifecycle
        }
    }
    

    这样比起直接在activity中实现要好些了,但是其解耦性还是不怎么好;在jetpack中,google提供了一个生命周期感知型组件——Lifecyle。
    Lifecyle是一个类,用于存储有关组件(如activity或者fragment)的生命周期状态的信息,并允许其他对象观察次状态,这些组件有助于编写出更有条理且往往更精简的代码,可以有效的实现activity和一些业务的解耦,更易于维护。
    Lifecyle的使用也比较简单,通过实现LifecycleObserver接口,OnLifecycleEvent注解来关联对应的生命周期,在activity或者fragment中通过Lifecycle的addObserver方法添加注册。

    dependencies {
        def lifecycle_version = "2.3.0"
        def arch_version = "2.1.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"
    
        // Saved state module for ViewModel
        implementation "androidx.lifecycle:lifecycle-viewmodel-savedstate:$lifecycle_version"
    
        // Annotation processor
        annotationProcessor "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:$lifecycle_version"
    
        // optional - Test helpers for LiveData
        testImplementation "androidx.arch.core:core-testing:$arch_version"
    }
    

    上面是一些依赖库,根据实际的需要进行添加。

    public interface LifecycleObserver {
    
    }
    

    LifecycleObserver目的是将一个类标记为LifecleObserver,它没有任何方法,通过依靠OnLifecycleEvent注释的方法;OnLifecycleEvent就是一个注解,通过Lifecycle中的Event枚举类标记对应的生命周期;

    @Retention(RetentionPolicy.RUNTIME)
    @Target(ElementType.METHOD)
    public @interface OnLifecycleEvent {
        Lifecycle.Event value();
    }
    
    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
        }
    

    Event中的元素对应activity或者fragment中的对应的生命周期;通过Lifecycle中的addObserver方法对LifecycleObserver进行注册;

    @Override
        public void addObserver(@NonNull LifecycleObserver observer) {
            //获取当前的状态 
            State initialState = mState == DESTROYED ? DESTROYED : INITIALIZED;
            //将LifecycleObserver和State进行绑定关联
            ObserverWithState statefulObserver = new ObserverWithState(observer, initialState);
            //LifecycleObserver实例对象为key ObserverWithState为value 存储在HashMap中
            ObserverWithState previous = mObserverMap.putIfAbsent(observer, statefulObserver);
    
            if (previous != null) {
                return;
            }
            //获取LifecycleOwner实例  LifecycleOwner是一个拥有安卓生命周期的接口 activity和fragment都实现了该接口
            LifecycleOwner lifecycleOwner = mLifecycleOwner.get();
            if (lifecycleOwner == null) {
                // it is null we should be destroyed. Fallback quickly
                return;
            }
    
            boolean isReentrance = mAddingObserverCounter != 0 || mHandlingEvent;
            //计算目标的State
            State targetState = calculateTargetState(observer);
            mAddingObserverCounter++;
            //statefulObserver.mState.compareTo(targetState) 当前LifecycleObserver的State和目标的State大小比较
            //mObserverMap.contains(observer) 到这里的话,LifecyclerObserver已经添加到HashMap中了
            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 V putIfAbsent(@NonNull K key, @NonNull V v) {
            //从HashMap中直接获取 如果有就直接返回从HashMap中获取的
            Entry<K, V> current = get(key);
            if (current != null) {
                return current.mValue;
            }
            //添加的HashMap中进行保存
            mHashMap.put(key, put(key, v));
            return null;
        }
    
    void dispatchEvent(LifecycleOwner owner, Event event) {
                State newState = getStateAfter(event);
                mState = min(mState, newState);
                mLifecycleObserver.onStateChanged(owner, event);
                mState = newState;
            }
    

    最终状态的改变会调用LifecycleEventObserver接口中的onStateChange方法,在系统的ComponentActivity的构造函数中,就注册了LifecycleEventObserver监听了;

    public ComponentActivity() {
            Lifecycle lifecycle = getLifecycle();
            //noinspection ConstantConditions
            if (lifecycle == null) {
                throw new IllegalStateException("getLifecycle() returned null in ComponentActivity's "
                        + "constructor. Please make sure you are lazily constructing your Lifecycle "
                        + "in the first call to getLifecycle() rather than relying on field "
                        + "initialization.");
            }
            if (Build.VERSION.SDK_INT >= 19) {
                getLifecycle().addObserver(new LifecycleEventObserver() {
                    @Override
                    public void onStateChanged(@NonNull LifecycleOwner source,
                            @NonNull Lifecycle.Event event) {
                        if (event == Lifecycle.Event.ON_STOP) {
                            Window window = getWindow();
                            final View decor = window != null ? window.peekDecorView() : null;
                            if (decor != null) {
                                decor.cancelPendingInputEvents();
                            }
                        }
                    }
                });
            }
            getLifecycle().addObserver(new LifecycleEventObserver() {
                @Override
                public void onStateChanged(@NonNull LifecycleOwner source,
                        @NonNull Lifecycle.Event event) {
                    if (event == Lifecycle.Event.ON_DESTROY) {
                        if (!isChangingConfigurations()) {
                            //如果不是因为配置改变导致activity销毁的话,在activity销毁时,就会去清空存储的ViewModel实例,
                            getViewModelStore().clear();
                        }
                    }
                }
            });
    
            if (19 <= SDK_INT && SDK_INT <= 23) {
                getLifecycle().addObserver(new ImmLeaksCleaner(this));
            }
        }
    

    LifecycleObserver已经注册好了,同时对State、Event等状态也进行了监听,那么当activity或者fragment生命周期改变是时如何告知监听者的呢?找到系统的FragmentActivity,会看到

    final LifecycleRegistry mFragmentLifecycleRegistry = new LifecycleRegistry(this);
    

    LifecycleRegistry是Lifecycle的实现类,可以处理多个观察者,找的FragmentActivity中的onCreate方法,

    @Override
        protected void onCreate(@Nullable Bundle savedInstanceState) {
            mFragments.attachHost(null /*parent*/);
    
            ......
    
            super.onCreate(savedInstanceState);
            //进行onCreate生命周期的处理 会设置当前的状态并通知观察者
            mFragmentLifecycleRegistry.handleLifecycleEvent(Lifecycle.Event.ON_CREATE);
            mFragments.dispatchCreate();
        }
    
    public void handleLifecycleEvent(@NonNull Lifecycle.Event event) {
        //获取State状态
            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;
        }
    

    在getStateAfter中根据生命周期进行了State状态的划分;

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

    可以看到onCreate和onStop是一致的,onStart和onPause是一致的,而对于State来说STARTED和RESUMED是处于活跃状态,其他的处于非活跃状态,得到State状态后,就会和之前保存的LifecycleObserver的状态进行对比,确定如何通知观察者;

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

    最终都是通过LifecycleObserver的onStateChanged方法回调通知的,onStart、onPause等生命周期中也都是一样的都是通过LifecycleRegistry实例中的handleLifecycleEvent方法去通知观察者activity或者fragment生命周期改变的;

    @Override
        protected void onPause() {
            super.onPause();
            mResumed = false;
            mFragments.dispatchPause();
            mFragmentLifecycleRegistry.handleLifecycleEvent(Lifecycle.Event.ON_PAUSE);
        }
    

    不过在使用的时候会发现如果继承的是AppCompactActivity或者FragmentActivity时,系统已经给实现这些了,可以通过

    getLifecycle().addObserver(new MyObserver());
    

    这样子进行注册,然后在对应的生命周期也都做了对应的处理,但是系统的Activity并没有实现LifeycleOwner接口,不过可以实现自定义的LifecycleOwner;

    public class MyActivity extends Activity implements LifecycleOwner {
        private LifecycleRegistry lifecycleRegistry;
    
        @Override
        protected void onCreate(@Nullable Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            lifecycleRegistry = new LifecycleRegistry(this);
            lifecycleRegistry.handleLifecycleEvent(Lifecycle.Event.ON_CREATE);
        }
    
        @Override
        protected void onStart() {
            super.onStart();
            lifecycleRegistry.handleLifecycleEvent(Lifecycle.Event.ON_START);
        }
    
        @Override
        protected void onStop() {
            super.onStop();
            lifecycleRegistry.handleLifecycleEvent(Lifecycle.Event.ON_STOP);
        }
    
        @Override
        protected void onResume() {
            super.onResume();
            lifecycleRegistry.handleLifecycleEvent(Lifecycle.Event.ON_RESUME);
        }
    
        @Override
        protected void onPause() {
            super.onPause();
            lifecycleRegistry.handleLifecycleEvent(Lifecycle.Event.ON_PAUSE);
        }
    
        @Override
        protected void onDestroy() {
            super.onDestroy();
            lifecycleRegistry.handleLifecycleEvent(Lifecycle.Event.ON_DESTROY);
        }
    
        @NonNull
        @Override
        public Lifecycle getLifecycle() {
            return lifecycleRegistry;
        }
    }
    

    然后后面的activity继承自MyActivity就可以了,这样就可以正常使用Lifecycle了,Fragment也是一样的,实现了LifecycleOwner接口,并在构造函数中初始化了LifecycleRegistry实例,

    private void initLifecycle() {
            mLifecycleRegistry = new LifecycleRegistry(this);
            mSavedStateRegistryController = SavedStateRegistryController.create(this);
            if (Build.VERSION.SDK_INT >= 19) {
                mLifecycleRegistry.addObserver(new LifecycleEventObserver() {
                    @Override
                    public void onStateChanged(@NonNull LifecycleOwner source,
                            @NonNull Lifecycle.Event event) {
                        if (event == Lifecycle.Event.ON_STOP) {
                            if (mView != null) {
                                mView.cancelPendingInputEvents();
                            }
                        }
                    }
                });
            }
        }
    

    然后在对应的生命周期通过handleLifecycleEvent方法通知观察者,不过需要注意的是它的调用并不是在生命周期回调方法中,而是在performCreate或者performStart等方法中;

    void performCreate(Bundle savedInstanceState) {
            mChildFragmentManager.noteStateNotSaved();
            mState = CREATED;
            mCalled = false;
            mSavedStateRegistryController.performRestore(savedInstanceState);
            onCreate(savedInstanceState);
            mIsCreated = true;
            if (!mCalled) {
                throw new SuperNotCalledException("Fragment " + this
                        + " did not call through to super.onCreate()");
            }
            mLifecycleRegistry.handleLifecycleEvent(Lifecycle.Event.ON_CREATE);
        }
    

    这样Lifecycle就可以轻松的感知activity和fragment的生命周期了。

    相关文章

      网友评论

          本文标题:Jetpack——Lifecyle使用和源码分析

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