美文网首页Android开发技术人扯技术Android技术知识
android Lifecycle源码分析--源码阅读100天(

android Lifecycle源码分析--源码阅读100天(

作者: a49f87ef5d4f | 来源:发表于2018-11-20 21:18 被阅读13次

    1.使用

    Lifecycle框架用来感知组件执行操作以响应另一个组件(例如Activity和Fragment)的生命周期状态的更改。这些组件可帮助您生成更易于组织且通常更轻量级的代码,这些代码更易于维护。
    举个例子:
    如果你需要在Activity或者Fragment的声明周期里做一些处理:

    override fun onCreate(savedInstanceState: Bundle?) {
            super.onCreate(savedInstanceState)
            presenter.onCreate()
        }
    override fun onStart(){
       super.onStart()
       presenter.onStart()
    }
    ...
    override fun onDestroy(){
       super.onDestroy()
       presenter.onDestroy()
    }
    

    这种写法需要在Activity或者Fragment的相应生命周期函数里调用presenter的相应方法,这种写法显得比较厚重,不够轻盈也没有解耦presenter和Activity,lifecycle的出现解决了这个问题

    class MainActivity : AppCompatActivity() {
    
        override fun onCreate(savedInstanceState: Bundle?) {
            super.onCreate(savedInstanceState)
            setContentView(R.layout.activity_main)
            lifecycle.addObserver(Presenter())
        }
    }
    
    class Presenter():LifecycleObserver {
    
        @OnLifecycleEvent(Lifecycle.Event.ON_CREATE)
        fun onCreate(){
    
            println("presenter oncreate")
    
        }
    
        @OnLifecycleEvent(Lifecycle.Event.ON_START)
        fun onStart(){
            println("presenter onstart")
        }
    
        @OnLifecycleEvent(Lifecycle.Event.ON_RESUME)
        fun onResumse(){
    
            println("presenter on resume")
        }
        @OnLifecycleEvent(Lifecycle.Event.ON_PAUSE)
        fun onPause(){
    
            println("presenter on pause")
        }
    
        @OnLifecycleEvent(Lifecycle.Event.ON_STOP)
        fun onStop(){
            println("presenter on stop")
        }
    
        @OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
        fun onDestroy(){
    
            println("presenter on destroy")
        }
    
    

    这样Presenter和Activity的关系就由关联关系转变为依赖关系,降低了耦合度,同时Presenter现在也可以用来感知Activity相应的生命周期,不用再在Activity的声明周期函数里调用Presenter的方法。

    2.分析

    2.1观察者模式

    通过接口和方法的名字大家就可以发现整个Lifecycle其实就是一个观察者模式,下面就是一个观察者模式的UML类图


    在这里插入图片描述

    那么duiyingLifecycle又是什么样的呢?下面是我自己画的一个Lifecycle的UML类图


    在这里插入图片描述
    我们自定义的Activity都继承自SupportActivity,可以发现SupportActivity实现了LifecycleOwner接口,同时持有实现了Lifecycle的LifecycleRegistry对象,这个对象就可以将其理解为观察者模式中的Subject,LifecycleRegistr聚合多个LifecycleObserver,生命周期改变时通知LifecycleObserver进行相应的方法调用。

    2.2生命周期感知

    Lifecycle是一个生命周期感知的框架,那么它是如何感知Activity的生命周期呢?看SupportActivity的onCretae方法

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

    在这里首先调用了ReportFragment.injectIfNeededIn(this)方法,看这个方法

    public static void injectIfNeededIn(Activity activity) {
            // ProcessLifecycleOwner should always correctly work and some activities may not extend
            // FragmentActivity from support lib, so we use framework fragments for activities
            android.app.FragmentManager manager = activity.getFragmentManager();
            if (manager.findFragmentByTag(REPORT_FRAGMENT_TAG) == null) {
                manager.beginTransaction().add(new ReportFragment(), REPORT_FRAGMENT_TAG).commit();
                // Hopefully, we are the first to make a transaction.
                manager.executePendingTransactions();
            }
        }
    

    很简单,就是在当前的Activity里添加一个ReportFragment。再看ReportFragment的生命周期函数。

     @Override
        public void onActivityCreated(Bundle savedInstanceState) {
            super.onActivityCreated(savedInstanceState);
            dispatchCreate(mProcessListener);
            dispatch(Lifecycle.Event.ON_CREATE);
        }
    
        @Override
        public void onStart() {
            super.onStart();
            dispatchStart(mProcessListener);
            dispatch(Lifecycle.Event.ON_START);
        }
    
        @Override
        public void onResume() {
            super.onResume();
            dispatchResume(mProcessListener);
            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);
            // just want to be sure that we won't leak reference to an activity
            mProcessListener = null;
        }
    
        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);
                }
            }
        }
    

    你会发现都调用了dispatch方法,而dispatch方法则会判断Activity是否实现了LifecycleOwner接口,如果实现了该接口就调用LifecycleRegister的handleLifecycleEvent,这样生命周期的状态就会借由LifecycleRegistry通知给各个LifecycleObserver从而调用其中对应Lifecycle.Event的方法。这种通过Fragment来感知Activity生命周期的方法其实在Glide的中也是有体现的。这是Activity的声明周期感知,那么Fragment呢?看一下Fragment源码你会发现Fragment也实现了LifecycleOwner接口,也关联了一个LifecycleRegistry对象

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

    看它的performCreate里调用了mLifecycleRegistry.handleLifecycleEvent,同理在performStart和performResume方法里也调用了。这里其实有个有趣的现象就是在ReportFragment中dispatch(Lifecycle.Event.ON_CREATE)这个方法是在onActivityCreated里调用的,而fragment的Lifecycle.Event.ON_CREATE的事件的发送是在performCreate里调用的,这就有个问题了,如果你在Activity里的onCreate方法里添加Fragment,同时这个Fragment也添加了LifecycleObserver的监听,那么谁先监听到呢?
    举个例子:

    class MainActivity : AppCompatActivity() {
    
        override fun onCreate(savedInstanceState: Bundle?) {
            super.onCreate(savedInstanceState)
            setContentView(R.layout.activity_main)
            lifecycle.addObserver(Presenter())
            supportFragmentManager.beginTransaction().replace(R.id.container,MainFragment()).commit()
        }
    
    }
    
    class Presenter:LifecycleObserver {
    
        @OnLifecycleEvent(Lifecycle.Event.ON_CREATE)
        fun onCreate(){
    
            println("presenter oncreate")
    
        }
    
    class MainFragment:Fragment() {
    
        override fun onCreate(savedInstanceState: Bundle?) {
            super.onCreate(savedInstanceState)
            lifecycle.addObserver(FragmentPresenter())
        }
    }
    
    class FragmentPresenter:LifecycleObserver {
    
        @OnLifecycleEvent(Lifecycle.Event.ON_CREATE)
        fun onCreate(){
    
            println("presenter fragment oncreate")
        }
    
    }
    

    运行程序你会发现打印结果是presenter oncreate,然后才是presenter fragment oncreate
    这就很疑惑了,我们知道fragment的声明周期onCreate是优先于onActivityCreated的,为什么没有先执行FragmentPresenter的onCreate方法,其实原因就在commit是异步的,提交fragment事物后会在何时的时机调用这个事物,所以此时MainFragment还没有被加入,但是ReportFragment调用了manager.executePendingTransactions()这个方法,这个方法会立即执行现有事物,所以这样ReportFragment就已经添加进FragmentManager了,所以出现了生命周期不对应的情况,如果你在MainActivity里MainFragment commit之后也添加manager.executePendingTransactions(),你就会发现打印结果是倒过来的。

    2.3LifecycleRegister分析

    LifecycleRegister是重点了先看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--;
        }
    
    

    这里你会发现生成了一个ObserverWithState,然后放入FastSafeIterableMap里,这个类
    是一个自定义列表,用于保存观察者并可在遍历期间处理删除/添加。
    观察者1和观察者2的任何时刻:如果addition_order(observer1)<addition_order(observer2),那么 state(observer1)> = state(observer2)
    接下来看handleLifecycleEvent方法

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

    首先会根据传入的Event得到相应的State,具体的对象关系在下图


    在这里插入图片描述

    在moveToState方法里,会调用sync方法

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

    这里可以看到如果ObserverWithState的state小于当前state,那么就调用forwardPass方法,如果大于当前state,那么就调用backwardPass方法,ObserverWithState默认的State是在addObserver方法里确定的

    State initialState = mState == DESTROYED ? DESTROYED : INITIALIZED;
            ObserverWithState statefulObserver = new ObserverWithState(observer, initialState);
    

    接着看forwardPass方法

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

    这里调用了ObserverWithState的dispatchEvent方法,看一下这个方法

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

    真相大白,最终调用了 mLifecycleObserver.onStateChanged(owner, event);同时更新了自己的state,这个mLifecycleObserver是怎么得到的,它又具体做了什么,就不具体说了,有兴趣的可以进去看一看,本片文章中的调用方法会生成一个ReflectiveGenericLifecycleObserver对象,这个对象会持有Presenter中声明了@OnLifecycleEvent注解的方法的Method对象,然后最终调用。

    qrcode_for_gh_075c7cccc4a0_344.jpg

    欢迎关注我的公众号

    相关文章

      网友评论

        本文标题:android Lifecycle源码分析--源码阅读100天(

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