我是靠谱客的博主 还单身小懒猪,最近开发中收集的这篇文章主要介绍Lifecycle使用及原理讲解,觉得挺不错的,现在分享给大家,希望可以做个参考。

概述

Lifecycle是Google在2017年的IO大会上推出的 Android Architecture Components中的一个,这个组件的用处就是可以感知Activity的生命周期,先来看下它的简单使用:

public class SecondActivity extends AppCompatActivity {
    private static final String TAG = "SecondActivity";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_second);
        getLifecycle().addObserver(new SimpleLifecycle());
        Log.d(TAG, "onCreate: this is activity onCreate()");
    }
    @Override
    protected void onStart() {
        super.onStart();
        Log.d(TAG, "onCreate: this is activity onStart()");
    }
    @Override
    protected void onResume() {
        super.onResume();
        Log.d(TAG, "onCreate: this is activity onResume()");
    }
    @Override
    protected void onPause() {
        super.onPause();
        Log.d(TAG, "onCreate: this is activity onPause()");
    }
    @Override
    protected void onStop() {
        super.onStop();
        Log.d(TAG, "onCreate: this is activity onStop()");
    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
        Log.d(TAG, "onCreate: this is activity onDestroy()");
    }

    private class SimpleLifecycle implements LifecycleObserver{
        @OnLifecycleEvent(Lifecycle.Event.ON_CREATE)
        private void onCreate(){
            Log.d(TAG, "onCreate: this is lifecycle onCreate()");
        }
        @OnLifecycleEvent(Lifecycle.Event.ON_START)
        private void onStart(){
            Log.d(TAG, "onCreate: this is lifecycle onStart()");
        }
        @OnLifecycleEvent(Lifecycle.Event.ON_RESUME)
        private void onResume(){
            Log.d(TAG, "onCreate: this is lifecycle onResume()");
        }
        @OnLifecycleEvent(Lifecycle.Event.ON_PAUSE)
        private void onPause(){
            Log.d(TAG, "onCreate: this is lifecycle onPause()");
        }
        @OnLifecycleEvent(Lifecycle.Event.ON_STOP)
        private void onStop(){
            Log.d(TAG, "onCreate: this is lifecycle onStop()");
        }
        @OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
        private void onDestroy(){
            Log.d(TAG, "onCreate: this is lifecycle onDestroy()");
        }
    }
}

再来看下打印的日志:

12-24 15:00:26.270 13079-13079/com.example.ubt.myapplication D/SecondActivity: onCreate: this is activity onCreate()
12-24 15:00:26.271 13079-13079/com.example.ubt.myapplication D/SecondActivity: onCreate: this is lifecycle onCreate()
    onCreate: this is activity onStart()
12-24 15:00:26.272 13079-13079/com.example.ubt.myapplication D/SecondActivity: onCreate: this is lifecycle onStart()
12-24 15:00:26.276 13079-13079/com.example.ubt.myapplication D/SecondActivity: onCreate: this is activity onResume()
    onCreate: this is lifecycle onResume()
12-24 15:00:41.009 13079-13079/com.example.ubt.myapplication D/SecondActivity: onCreate: this is lifecycle onPause()
12-24 15:00:41.010 13079-13079/com.example.ubt.myapplication D/SecondActivity: onCreate: this is activity onPause()
12-24 15:00:41.467 13079-13079/com.example.ubt.myapplication D/SecondActivity: onCreate: this is lifecycle onStop()
    onCreate: this is activity onStop()
12-24 15:00:41.468 13079-13079/com.example.ubt.myapplication D/SecondActivity: onCreate: this is lifecycle onDestroy()
12-24 15:00:41.469 13079-13079/com.example.ubt.myapplication D/SecondActivity: onCreate: this is activity onDestroy()

从日志中可以看到SimpleLifecycle 感知到了Activity的生命周期,用法有两点需要主要

  1. 实现LifecycleObserver接口,这是一个空接口,要对应到activity的生命周期,需要@OnLifecycleEvent这个注解,这个注解需要传一个值Lifecycle.Event,这个值就代表activity对应的生命周期,下面的方法名可以随意定义;
  2. 接下来调用getLifecycle().addObserver(new SimpleLifecycle());这个方法就可以了,传入实现LifecycleObserver接口的对象就可以了。
    使用就是这么简单,那其中的原理又是什么呢?如果要你实现,你会怎么去实现呢?看到这样一个功能,我首先想到的就是利用fragment,毕竟fragment拥有和activity相同的生命周期,那到底是不是呢?这里先来验证下,实现activity的onAttachFragment方法:
onAttachFragment(android.app.Fragment fragment){
	Log.d(TAG, "onAttachFragment: fragment = "+fragment);
} 

注意这里传入的参数,看看里面是不是有fragment给我们返回,再来看下打印结果:
12-24 16:13:05.682 20810-20810/com.example.ubt.myapplication D/SecondActivity: onAttachFragment: fragment = m{9fb1708 #0 android.arch.lifecycle.LifecycleDispatcher.report_fragment_tag}
可以看到确实是利用fragment实现的,接下来再去看看源码是如何实现的,这里的入口是getLifecycle(),跟着这个方法下去,最终来到SupportActivity,这里就是为了实现Lifecycle单独提出来的activity,不长,那就全部来看看:

public class SupportActivity extends Activity implements LifecycleOwner {
    /**
     * Storage for {@link ExtraData} instances.
     *
     * <p>Note that these objects are not retained across configuration changes</p>
     */
    private SimpleArrayMap<Class<? extends ExtraData>, ExtraData> mExtraDataMap =
            new SimpleArrayMap<>();

    private LifecycleRegistry mLifecycleRegistry = new LifecycleRegistry(this);

    /**
     * Store an instance of {@link ExtraData} for later retrieval by class name
     * via {@link #getExtraData}.
     *
     * <p>Note that these objects are not retained across configuration changes</p>
     *
     * @see #getExtraData
     * @hide
     */
    @RestrictTo(LIBRARY_GROUP)
    public void putExtraData(ExtraData extraData) {
        mExtraDataMap.put(extraData.getClass(), extraData);
    }

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

    @CallSuper
    @Override
    protected void onSaveInstanceState(Bundle outState) {
        mLifecycleRegistry.markState(Lifecycle.State.CREATED);
        super.onSaveInstanceState(outState);
    }

    /**
     * Retrieves a previously set {@link ExtraData} by class name.
     *
     * @see #putExtraData
     * @hide
     */
    @RestrictTo(LIBRARY_GROUP)
    public <T extends ExtraData> T getExtraData(Class<T> extraDataClass) {
        return (T) mExtraDataMap.get(extraDataClass);
    }

    @Override
    public Lifecycle getLifecycle() {
        return mLifecycleRegistry;
    }

    /**
     * @hide
     */
    @RestrictTo(LIBRARY_GROUP)
    public static class ExtraData {
    }
}

这里有mExtraDataMap和mLifecycleRegistry 两个属性,一开始就初始化了,下面的方法都是围绕这两个属性展开的,mExtraDataMap就是一个保存数据的集合,这个很好理解,接下来重点要看的就是mLifecycleRegistry ,不过在这之前还是先来看看onCreate()方法中的ReportFragment.injectIfNeededIn(this)这段代码,嗯…,那看来得去看看ReportFragment了,这个类也不长,就全部来看看:

public class ReportFragment extends Fragment {
    private static final String REPORT_FRAGMENT_TAG = "android.arch.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();
        }
    }

    static ReportFragment get(Activity activity) {
        return (ReportFragment) activity.getFragmentManager().findFragmentByTag(
                REPORT_FRAGMENT_TAG);
    }

    private ActivityInitializationListener mProcessListener;

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

    void setProcessListener(ActivityInitializationListener processListener) {
        mProcessListener = processListener;
    }

    interface ActivityInitializationListener {
        void onCreate();

        void onStart();

        void onResume();
    }
}

先来看看injectIfNeededIn()这个方法,这里面的逻辑很好理解,就是在activity中添加当前这个fragment,这样ReportFragment 就拥有了和activity一样的生命周期了(看来和前面猜想差不多了),再来看看其中的一个生命周期方法,这里就选onResume()了,先调用了dispatchResume(mProcessListener),这里默认mProceListener为null,再来看dispatch(Lifecycle.Event.ON_RESUME):

    private void dispatch(Lifecycle.Event event) {
        Activity activity = getActivity();
        //在新的版本中LifecycleRegistryOwner已经被废弃,由下面的LifecycleOwner替代了
        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);
            }
        }
    }

在新的版本中会执行下面的if语句,还记得前面SupportActivity的属性mLifecycleRegistry么,这里getLifecycle()返回的就是这个属性,它的类型是LifecycleRegistry,这里调用了它的handleLifecycleEvent(event)方法,看来handleLifecycleEvent(event)会去分发activity生命周期事件,那么现在再回过看:
mLifecycleRegistry = new LifecycleRegistry(this),那就再来看看LifecycleRegistry这个类是如何去分发事件的,切入点就是handleLifecycleEvent(event)这个方法:

    public void handleLifecycleEvent(@NonNull Lifecycle.Event event) {
    	//根据event判断当前是在那个生命周期里
        State next = getStateAfter(event);
        //知道了当前所处的生命周期,就可以去执行已经注册的LifecycleObserver对应的生命周期方法
        moveToState(next);
    }
    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);
    }

    private void moveToState(State next) {
    	//如果当前所处的状态与要执行的状态一致就没必要再去执行了,直接返回
        if (mState == next) {
            return;
        }
        mState = next;
        //mHandlingEvent表示是否正在处理状态,mAddingObserverCounter表示当前通过addObserver()添加进来的LifecycleObserver,如果当前正在处理状态并且mAddingObserverCounter的不为0就直接返回,意思就是说当前正在处理状态的时候添加了LifecycleObserver进来(可能是在回调中添加的),那么这时候在这里就直接返回了
        if (mHandlingEvent || mAddingObserverCounter != 0) {
            mNewEventOccurred = true;
            // we will figure out what to do on upper level.
            return;
        }
        mHandlingEvent = true;
        //这里就是对状态的同步了
        sync();
        mHandlingEvent = false;
    }

接着就来看看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循环就是判断是否把所有添加进来的LifecycleObserver的状态全部同步完成了
        while (!isSynced()) {
        	//这里置false,当在执行回调时置为true,可以让后面执行的函数更快的返回
            mNewEventOccurred = false;
            // no need to check eldest for nullability, because isSynced does it for us.
            //mObserverMap里的元素的状态是非递增排列的,这样eldest的state最大,newest的state最小
            //同步状态时分为两种情况,一是执行:onCreate(),onStart(),onResume(),这种对应下面的forwardPass()方法
            //二是执行:onPause(),onStop(),onDestroy(),对应下面的backwardPass()方法
            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;
    }

通过对上面代码的分析,生命周期事件分发由backwardPass()和forwardPass()去执行,这里就主要说下backwardPass(),明白backwardPass()也就明白forwardPass()了:

    private void backwardPass(LifecycleOwner lifecycleOwner) {
    //这里是对mObserverMap进行降序迭代
        Iterator<Entry<LifecycleObserver, ObserverWithState>> descendingIterator =
                mObserverMap.descendingIterator();
        while (descendingIterator.hasNext() && !mNewEventOccurred) {
            Entry<LifecycleObserver, ObserverWithState> entry = descendingIterator.next();
            //这里就是获取添加进来的LifecycleObserver,然后在进行状态的分发
            ObserverWithState observer = entry.getValue();
            while ((observer.mState.compareTo(mState) > 0 && !mNewEventOccurred
                    && mObserverMap.contains(entry.getKey()))) {
                //这里就是根据现在所处的状态判断接下来该执行的状态,比如现在要执行onPause()方法,那么所处的状态是RESUMED的,看downEvent() 的方法,返回的是ON_PAUSE,那就说接下来要执行的是onPause()方法
                Event event = downEvent(observer.mState);
                pushParentState(getStateAfter(event));
                //这里就是对状态的分发,进而转化为对应的生命周期事件,这里就不在跟下去了
                observer.dispatchEvent(lifecycleOwner, event);
                popParentState();
            }
        }
    }
    private static Event downEvent(State state) {
        switch (state) {
            case INITIALIZED:
                throw new IllegalArgumentException();
            case CREATED:
                return ON_DESTROY;
            case STARTED:
                return ON_STOP;
            case RESUMED:
                return ON_PAUSE;
            case DESTROYED:
                throw new IllegalArgumentException();
        }
        throw new IllegalArgumentException("Unexpected state value " + state);
    }

到这里为止,生命周期对应事件的分发差不多就理了一遍,不过记住一点,生命周期的分发实际是通过fragment去实现的。
最后再来看下添加LifecycleObserver 的逻辑:

    public void addObserver(@NonNull LifecycleObserver observer) {
        State initialState = mState == DESTROYED ? DESTROYED : INITIALIZED;
        //对observer进行一层封装,这里面会对observer的注解进行处理,生成一个adapter
        ObserverWithState statefulObserver = new ObserverWithState(observer, initialState);
        //将observer保存起来,后面同步状态时就是通过遍历这个集合
        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;
        //计算当前的状态,已确定需要执行的状态,比如observer是在onResume()添加进来的,那么这时候就需要去执行observer的onCreate()和onStart()方法,下面同步状态主要也是这个作用
        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--;
    }

这样,整个流程就梳理完了,如有不对的地方欢迎指正,一起学习。


参考资料: Android arch components 源码分析(2)—— Lifecycle

最后

以上就是还单身小懒猪为你收集整理的Lifecycle使用及原理讲解的全部内容,希望文章能够帮你解决Lifecycle使用及原理讲解所遇到的程序开发问题。

如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(34)

评论列表共有 0 条评论

立即
投稿
返回
顶部