原创

Lifecycle 使用与源码分析——彻底搞懂Lifecycle原理

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://xuexuan.blog.csdn.net/article/details/90749168

一、Lifecycle 介绍

Lifecycle是一个生命周期感知组件,一般用来响应Activity、Fragment等组件的生命周期变化,并将变化通知到已注册的观察者。有助于更好地组织代码,让代码逻辑符合生命周期规范,减少内存泄漏,增强稳定性。

这些组件可帮助您生成更易于组织且通常更轻量级的代码,这些代码更易于维护。

二、使用方法

先来看一下如何使用,这样再去分析源码就能有的放矢,

1.添加依赖:

在app或者module目录下的build.gradle中,添加依赖:

这里介绍Androidx 项目引入lifecycle

dependencies {
  implementation "androidx.lifecycle:lifecycle-runtime:2.0.0"
  implementation "androidx.lifecycle:lifecycle-extensions:2.0.0"
  implementation "androidx.lifecycle:lifecycle-common-java8:2.0.0"
  annotationProcessor  "androidx.lifecycle:lifecycle-compiler:2.0.0"
}

2.LifecycleObserver接口

实现LifecycleObserver接口,有两种方式:
1、直接实现LifecycleObserver 接口,使用 @OnLifecycleEvent注解在方法上,注解值表示该方法对应生命周期的哪个函数
2、实现DefaultLifecycleObserver 接口,并实现其中的方法。官方建议Java 8 中,使用这种方式

下面看一下这两种方式的代码实现:

第一种:

public class LifecycleObserver1 implements LifecycleObserver {
    private static final String TAG = Java7Observer.class.getSimpleName();

    @OnLifecycleEvent(Lifecycle.Event.ON_CREATE)
    public void onCreate() { Log.d(TAG, "onCreate"); }

    @OnLifecycleEvent(Lifecycle.Event.ON_START)
    public void onStart() { Log.d(TAG, "onStart"); }

    @OnLifecycleEvent(Lifecycle.Event.ON_RESUME)
    public void onResume() { Log.d(TAG, "onResume"); }

    @OnLifecycleEvent(Lifecycle.Event.ON_PAUSE)
    public void onPause() { Log.d(TAG, "onPause"); }

    @OnLifecycleEvent(Lifecycle.Event.ON_STOP)
    public void onStop() { Log.d(TAG, "onStop"); }

    @OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
    public void onDestroy() { Log.d(TAG, "onDestroy"); }
}

第二种:

DefaultLifecycleObserver 继承了 FullLifecycleObserver 继承了 LifecycleObserver

public class LifecycleObserver2 implements DefaultLifecycleObserver {
    private static final String TAG = Java8Observer.class.getSimpleName();

    @Override
    public void onCreate(@NonNull LifecycleOwner owner) { Log.d(TAG, "onCreate"); }

    @Override
    public void onStart(@NonNull LifecycleOwner owner) { Log.d(TAG, "onStart"); }

    @Override
    public void onResume(@NonNull LifecycleOwner owner) { Log.d(TAG, "onResume"); }

    @Override
    public void onPause(@NonNull LifecycleOwner owner) { Log.d(TAG, "onPause"); }

    @Override
    public void onStop(@NonNull LifecycleOwner owner) { Log.d(TAG, "onStop"); }

    @Override
    public void onDestroy(@NonNull LifecycleOwner owner) { Log.d(TAG, "onDestroy"); }
}

3.将LifecycleObserver添加到Lifecycle的观察者列表

如果你使用新版本的AppcompatActivity(>26.1.0),因为 AppCompatActivity 实现了 LifecycleOwner接口,所以可以这么写:

public class MainActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        // 直接调用getLifecycle(),添加Observer
        getLifecycle().addObserver(new LifecycleObserver1 ());
        getLifecycle().addObserver(new LifecycleObserver2 ());
    }
}

当然也可以自己实现 LifecycleOwner接口,需要做3件事情

1、实现LifecycleOwner 接口的方法:getLifecycle()
2、注册Lifecycle new LifecycleRegistry(this)
3、在Activity生命周期函数中分发事件

public class MainActivity extends Activity implements LifecycleOwner {
    private LifecycleRegistry mLifecycleRegistry;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mLifecycleRegistry = new LifecycleRegistry(this);
        mLifecycleRegistry.handleLifecycleEvent(Lifecycle.Event.ON_CREATE);
        mLifecycleRegistry.addObserver(new TestObserver());
    }

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

    @Override
    public void onStart() {
        super.onStart();
        mLifecycleRegistry.handleLifecycleEvent(Lifecycle.Event.ON_START);
    }

    @Override
    public void onResume() {
        super.onResume();
        mLifecycleRegistry.handleLifecycleEvent(Lifecycle.Event.ON_RESUME);
    }

    @Override
    public void onPause() {
        mLifecycleRegistry.handleLifecycleEvent(Lifecycle.Event.ON_PAUSE);
        super.onPause();
    }

    @Override
    public void onStop() {
        mLifecycleRegistry.handleLifecycleEvent(Lifecycle.Event.ON_STOP);
        super.onStop();
    }

    @Override
    public void onDestroy() {
        mLifecycleRegistry.handleLifecycleEvent(Lifecycle.Event.ON_DESTROY);
        super.onDestroy();
    }
}

举个例子:

如果你需要在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的方法。

三、源码分析

3.1 Lifecycle相关的类图

先来看一下 Lifecycle相关的类图
在这里插入图片描述

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

3.2、生命周期感知

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

看AppCompatActivity 继承的ComponentActivity 中的onCretae方法

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

ReportFragment 类是一个Fragment,它负责分派生命周期的时间.
injectIfNeededIn()就是在当前的Activity里添加一个ReportFragment。

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

再看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对象

3.3、LifecycleRegister分析

把LifecycleObserver (观察者)添加到 Lifecycle(被观察者)的列表中,使用的是addObserver,而在源代码中,实现Lifecycle接口的是LifecycleRegister

    getLifecycle().addObserver(new LifecycleObserver1 ());

来看一下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--;
    }

其中mObserverMap 是FastSafeIterableMap

    private FastSafeIterableMap<LifecycleObserver, ObserverWithState> mObserverMap = new FastSafeIterableMap<>();

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

前面提到了,每当生命周期发生变化,最终都会调用dispatch方法中的handleLifecycleEvent方法

下面来看下handleLifecycleEvent方法的代码:

 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) {
            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方法里确定的,如果不是DESTROYED状态,就初始为 INITIALIZED

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

上面的observer其实是一个ObserverWithState对象,它是一个静态内部类

    static class ObserverWithState {
        State mState;
        GenericLifecycleObserver mLifecycleObserver;

        ObserverWithState(LifecycleObserver observer, State initialState) {
            mLifecycleObserver = Lifecycling.getCallback(observer);
            mState = initialState;
        }

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

调用了Lifecycling.getCallback方法来获得GenericLifecycleObserver 的实例,通过这个实例调用onStateChanged

    @NonNull
    static GenericLifecycleObserver getCallback(Object object) {
        if (object instanceof FullLifecycleObserver) {
            return new FullLifecycleObserverAdapter((FullLifecycleObserver) object);
        }

        if (object instanceof GenericLifecycleObserver) {
            return (GenericLifecycleObserver) object;
        }

        final Class<?> klass = object.getClass();
        int type = getObserverConstructorType(klass);
        if (type == GENERATED_CALLBACK) {
            List<Constructor<? extends GeneratedAdapter>> constructors =
                    sClassToAdapters.get(klass);
            if (constructors.size() == 1) {
                GeneratedAdapter generatedAdapter = createGeneratedAdapter(
                        constructors.get(0), object);
                return new SingleGeneratedAdapterObserver(generatedAdapter);
            }
            GeneratedAdapter[] adapters = new GeneratedAdapter[constructors.size()];
            for (int i = 0; i < constructors.size(); i++) {
                adapters[i] = createGeneratedAdapter(constructors.get(i), object);
            }
            return new CompositeGeneratedAdaptersObserver(adapters);
        }
        return new ReflectiveGenericLifecycleObserver(object);
    }

这个方法大概意思就是,根据传进的LifecycleObserver进行判断,构造一个GenericLifecycleObserver()的对象.

GenericLifecycleObserver有四种实现:

  1. FullLifecycleObserverAdapter
  2. SingleGeneratedAdapterObserver
  3. CompositeGeneratedAdaptersObserver
  4. ReflectiveGenericLifecycleObserver

对应的实现原理有三种,

  1. 使用实现LifecycleObserver接口的第二种方法,生成对应的FullLifecycleObserverAdapter类

  2. 使用实现LifecycleObserver接口的第一种方法,也就是在方法上加入注解,注解值代表生命周期。annotationProcessor "androidx.lifecycle:lifecycle-compiler:2.0.0" 这是注解处理器的依赖,引入这个之后,会自动生成xxx_LifecycleAdapter的文件。会生成对应的SingleGeneratedAdapterObserver、CompositeGeneratedAdaptersObserver类

  3. ReflectiveGenericLifecycleObserver,通过反射,去调用方法

GenericLifecycleObserver 的实例如何生成分析完了,接下来就是调用onStateChanged(),来通知 实现了 LifecycleObserver的类,生命周期发生了变化

四、Lifecycle为什么要使用Fragment

Lifecycle为什么要使用Fragment,为什么不直接把这些方法,在Activity中实现呢?

我个人认为有两个原因:

  1. 因为不是所有的页面都继承AppCompatActivity,为了兼容非AppCompatActivity
  2. Activity和Fragment都实现Lifecycle,避免代码重复

所以封装一个同样具有生命周期的Fragment来给Lifecycle分发生命周期事件。

参考:
https://blog.csdn.net/xfhy_/article/details/88543884
https://juejin.im/post/5bf3cb46f265da612239f612
https://www.jianshu.com/p/2c9bcbf092bc

文章最后发布于: 2019-06-03 15:50:36
展开阅读全文
0 个人打赏

没有更多推荐了,返回首页

©️2019 CSDN 皮肤主题: 代码科技 设计师: Amelia_0503

分享到微信朋友圈

×

扫一扫,手机浏览