3. Jetpack源码解析---用Lifecycles管理生命周期

Posted Hankkin_Coding

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了3. Jetpack源码解析---用Lifecycles管理生命周期相关的知识,希望对你有一定的参考价值。

1. 背景

上一篇我门对Jetpack组件中的Navigation做了介绍,并且对其做了源码分析,相信看过之后已经对此有了一定的了解,本篇文章我们会对Lifecycles进行使用及源码的介绍,还没看上篇的可以看一下:

系列文章

1. Jetpack源码解析—看完你就知道Navigation是什么了?

2. Jetpack源码解析—Navigation为什么切换Fragment会重绘?

2. 基础


2.1 简介

Lifecycles是一个持有组件生命周期状态(如Activity、Fragment)信息的类,并允许其他对象观察此状态。可以帮助我们方便的管理ActivityFragment的生命周期。

Lifecycle组件中通过两个枚举类来跟踪其关联组件的生命周期:


2.2 基本使用

在我们的日常开发中,经常需要我们在Activity或者Fragment的生命周期方法中手动去管理一下资源的释放等行为。举个简单的例子,当我们做自定义相机扫描的时候,camera相关的资源就需要我们手动的去释放及开启预览;或者我们在使用MVP模式去开发的时候,P的创建和销毁也需要我们在生命周期方法中去操作。

通过Lifecycles组件我们可以这样使用:

我们可以定义一个Observer实现LifecycleObserver,并且在Activity或者Fragment中进行观察:

/**
 * created by $Hankkin
 * on 2019-06-10
 */

class MyObserver : LifecycleObserver 

    @OnLifecycleEvent(Lifecycle.Event.ON_START)
    fun onStart() 
        Log.e(javaClass.name, "-------onStart")
    

    @OnLifecycleEvent(Lifecycle.Event.ON_CREATE)
    fun onCreate() 
        Log.e(javaClass.name, "-------onCreate")
    

    @OnLifecycleEvent(Lifecycle.Event.ON_RESUME)
    fun onResume() 
        Log.e(javaClass.name, "-------onResume")
    

    @OnLifecycleEvent(Lifecycle.Event.ON_PAUSE)
    fun onPause() 
        Log.e(javaClass.name, "-------onPause")
    


    @OnLifecycleEvent(Lifecycle.Event.ON_STOP)
    fun onStop() 
        Log.e(javaClass.name, "-------onStop")
    


    @OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
    fun onDestroy() 
        Log.e(javaClass.name, "-------onDestroy")
    


下面是Activity:

class MainActivity : AppCompatActivity() 
    
    override fun onCreate(savedInstanceState: Bundle?) 
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)


        lifecycle.addObserver(MyObserver())
        Log.e(javaClass.name, "-------onCreate")

    

    override fun onStart() 
        super.onStart()
        Log.e(javaClass.name, "-------onStart")
    

    override fun onResume() 
        super.onResume()
        Log.e(javaClass.name, "-------onResume")
    

    override fun onPause() 
        super.onPause()
        Log.e(javaClass.name, "-------onPause")
    

    override fun onStop() 
        super.onStop()
        Log.e(javaClass.name, "-------onStop")
    

    override fun onDestroy() 
        super.onDestroy()
        Log.e(javaClass.name, "-------onDestroy")
    

启动Activity,我们可以看到控制台中的打印日志:

MainActivity: -------onCreate
MyObserver: -------onCreate
MainActivity: -------onStart
MyObserver: -------onStart
MainActivity: -------onResume
MyObserver: -------onResume
......

通过控制台打印我们可以看到我们的观察者Activity和被观察者的日志均被打印了。具体是怎么实现的呢?


3. 源码分析

通过代码我们大概能看出来Lifecycles组件是通过观察者模式来实现的,接下来我们具体分析实现原理,我们发现在ActivityFragment中可以直接通过getLifecycle()方法获取到Lifecycle,那么我们就从这里入手:


3.1 getLifecycle()

我们点击进去发现ComponentActivity中实现了LifecycleOwner接口,LifecycleOwner接口中则声明了getLifecycle()方法,而ComponentActivity中直接返回了mLifecycleRegistry

public class ComponentActivity extends androidx.core.app.ComponentActivity implements
        LifecycleOwner,
        ViewModelStoreOwner,
        SavedStateRegistryOwner,
        OnBackPressedDispatcherOwner 

    private final LifecycleRegistry mLifecycleRegistry = new LifecycleRegistry(this);
    ......
    @NonNull
    @Override
    public Lifecycle getLifecycle() 
        return mLifecycleRegistry;
    

LifecycleRegistry是个什么东西呢?原来它继承了Lifecycle

public class LifecycleRegistry extends Lifecycle


3.2 Lifecycle和LifecycleRegistry

我们看一下Lifecycle类:

public abstract class Lifecycle 

        //注册LifecycleObserver (比如Presenter)
        public abstract void addObserver(@NonNull LifecycleObserver observer);
        //移除LifecycleObserver 
        public abstract void removeObserver(@NonNull LifecycleObserver observer);
        //获取当前状态
        public abstract State getCurrentState();

        public enum Event 
            ON_CREATE,
            ON_START,
            ON_RESUME,
            ON_PAUSE,
            ON_STOP,
            ON_DESTROY,
            ON_ANY
        
        
       public enum State 
            DESTROYED,
            INITIALIZED,
            CREATED,
            STARTED,
            RESUMED;

            public boolean isAtLeast(@NonNull State state) 
                return compareTo(state) >= 0;
            
       

Lifecycle中就是声明了一些抽象方法和两个状态的枚举类,具体的实现看LifecycleRegistry

public class LifecycleRegistry extends Lifecycle 

// LifecycleObserver Map,每一个Observer都有一个State
    private FastSafeIterableMap<LifecycleObserver, ObserverWithState> mObserverMap = new FastSafeIterableMap<>();
    // 当前的状态
    private State mState;
    // 生命周期拥有者,ComponentActivity继承了LifecycleOwner
    private final WeakReference<LifecycleOwner> mLifecycleOwner;

    //修改State值
    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;
    

    /**
    * 添加LifecycleObserver观察者,并将之前的状态分发给这个Observer,例如我们在onResume之后注册这个Observer,
    * 该Observer依然能收到ON_CREATE事件
    */
    @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);
        ......
        // 例如:Observer初始状态是INITIALIZED,当前状态是RESUMED,需要将INITIALIZED到RESUMED之间的
        // 所有事件分发给Observer
        while ((statefulObserver.mState.compareTo(targetState) < 0
                && mObserverMap.contains(observer))) 
            pushParentState(statefulObserver.mState);
            statefulObserver.dispatchEvent(lifecycleOwner, upEvent(statefulObserver.mState));
            popParentState();
            targetState = calculateTargetState(observer);
        
        ......


/**
     * 同步Observer状态,并分发事件
     */
    private void sync() 
        LifecycleOwner lfecycleOwner = 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;
            // State中,状态值是从DESTROYED-INITIALIZED-CREATED-STARTED-RESUMED增大
            // 如果当前状态值 < Observer状态值,需要通知Observer减小状态值,直到等于当前状态值
            if (mState.compareTo(mObserverMap.eldest().getValue().mState) < 0) 
                backwardPass(lifecycleOwner);
            
            Entry<LifecycleObserver, ObserverWithState> newest = mObserverMap.newest();
            // 如果当前状态值 > Observer状态值,需要通知Observer增大状态值,直到等于当前状态值
            if (!mNewEventOccurred && newest != null
                    && mState.compareTo(newest.getValue().mState) > 0) 
                forwardPass(lifecycleOwner);
            
        
        mNewEventOccurred = false;
    

    /**
     * 向前传递事件,对应图中的INITIALIZED -> RESUMED
     * 增加Observer的状态值,直到状态值等于当前状态值
     */
    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();
            
        
    

    /**
     * 向后传递事件,对应图中的RESUMED -> DESTROYED
     * 减小Observer的状态值,直到状态值等于当前状态值
     */
    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();
            
        
    

LifecycleRegistry代码我门看完了,注释也已经很清楚了,基本作用就是添加观察者,响应生命周期事件,分发生命周期事件的作用。


3.3 ReportFragment

接下来我们继续分析ComponentActivity,我们在onCreate()声明周期中发现一个比较熟悉ReportFragment,这个fragment我以前在做内存泄漏优化的时候经常碰到,在leakcanary中经常会报出这个类,所以这里面看看ReportFragment.injectIfNeededIn(this);到底做了什么?

@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP_PREFIX)
public class ReportFragment extends Fragment 
    private static final String REPORT_FRAGMENT_TAG = "androidx.lifecycle"
            + ".LifecycleDispatcher.report_fragment_tag";

    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();
        
    
    private void dispatchCreate(ActivityInitializationListener listener) 
        if (listener != null) 
            listener.onCreate();
        
    

    private void dispatchStart(ActivityInitializationListener listener) 
        if (listener != null) 
            listener.onStart();
        
    

    private void dispatchResume(ActivityInitializationListener listener) 
        if (listener != null) 
            listener.onResume();
        
    

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

查看源码我们发现,ReportFragment在每个生命周期中都做了分发事件的处理,通过调用getLifecycle().handleLifecycleEvent(event)来做生命周期的分发。意思也就是在ComponentActivity中添加了一个没有页面的ReportFragment,当Activity生命周期变化的时候,通过调用LifecycleRegistry.handleLifecycleEvent()方法通知LifecycleRegistry改变状态,LifecycleRegistry内部调用moveToState()改变状态,并调用每个LifecycleObserver.onStateChange()方法通知生命周期变化。

我们通过查看ReportFragment调用,发现还有两个类也调用了它,一个是LifecycleDispatcher,一个是ProcessLifecycleOwner,这两个究竟是做什么的呢?

[外链图片转存失败(img-Kmu4o9EL-1562754821909)(http://psv0rasgi.bkt.clouddn.com/jetpack/_image/2019-06-10/屏幕快照 2019-06-11 下午2.19.20 (2).png#align=left&display=inline&height=324&originHeight=648&originWidth=1112&status=done&width=556)]


3.4 LifecycleDispatcher

class LifecycleDispatcher 

    private static AtomicBoolean sInitialized = new AtomicBoolean(false);

    static void init(Context context) 
        if (sInitialized.getAndSet(true)) 
            return;
        
        ((Application) context.getApplicationContext())
                .registerActivityLifecycleCallbacks(new DispatcherActivityCallback());
    

    @SuppressWarnings("WeakerAccess")
    @VisibleForTesting
    static class DispatcherActivityCallback extends EmptyActivityLifecycleCallbacks 

        @Override
        public void onActivityCreated(Activity activity, Bundle savedInstanceState) 
            ReportFragment.injectIfNeededIn(activity);
        

        @Override
        public void 以上是关于3. Jetpack源码解析---用Lifecycles管理生命周期的主要内容,如果未能解决你的问题,请参考以下文章

4. Jetpack源码解析—LiveData的使用及工作原理

4. Jetpack源码解析—LiveData的使用及工作原理

4. Jetpack源码解析—LiveData的使用及工作原理

5. Jetpack源码解析---ViewModel基本使用及源码解析

5. Jetpack源码解析---ViewModel基本使用及源码解析

5. Jetpack源码解析---ViewModel基本使用及源码解析