Android架构组件系列-Lifecycle源码详解

概述

Google 官方发布了Android 框架组件库(Android Architecture Components),目的为了帮助开发者开发更健壮,便于测试和维护的应用。框架主要用来管理UI组件(Activity或Fragment)的生命周期,提供持久化数据的方式

痛点问题

问题一:在简化Activity或Fragment(下称UI组件)中代码逻辑时,我们发现,与生命周期相关的逻辑很难从UI组件中迁移出去,导致UI组件部分关键生命周期回调中的代码很臃肿(强迫症重度患者),十分不易维护。
问题二: 由于移动设备资源有限,Android系统随时都可能会杀死一些应用程序(按照一定的规则或者说根据应用的状态和其优先级),以腾出空间给新的应用。此时,UI组件的生命周期(这里主要是指销毁)就不在我们的控制之下了,所以,如果我们将用户数据直接存储在UI组件中,又没做一些比较麻烦的保护措施,那么组件中的用户数据就GG了。

架构库内容

Lifecycle:帮助我们轻松的管理UI组件的生命周期,当组件的生存状态改变时,可以避免内存泄漏的问题,并且能轻松的将数据重新加载到UI中。

LiveData:一个数据持有类,持有数据并且这个数据可以被观察(一般观察者就是UI组件啦),当其持有的数据发生变化时,能通知到他的观察者们(嗯,这很强)。

ViewModel:用于存储UI相关数据(LiveData咯),作为UI组件和数据的桥梁,将数据和组件分离,完成了持久化和保护数据的任务。

Room:谷歌推出的一个SQLite对象映射库,使用注解,极大简化数据库的操作。还能在编译时检查SQLite语句,可以返回RxJava,Flowable和LiveData Observable。

架构图:下面这张图是Android架构组件完整的架构图,其中表示了的架构组件的所有模块以及它们之间如何交互

终极版架构图
框架补充:如果不满足官方的库其实可以自己实现。比如LiveData在某些情况下可使用RxJava代替。数据层官方推荐使用Room或者Realm或者其他SQLite ORM等都可以。网络请求推荐使用Retrofit。各层之间的耦合推荐使用服务发现者模式(Service Locator)或者依赖注入(DI),推荐Dagger2。

Lifecycle详解

架构组件较多,本文主要讲解Lifecycle,其他组件会在后续的文章中介绍。

Lifecycle解决了什么问题?

UI组件的生命周期是由Android系统或者framework层代码管理的,我们是无法控制的,只能在生命周期的回调方法里(onCreate等)做一些处理。
很多时候,我们的很多操作都需要写在生命周期的回调方法中,比如,注册或者销毁(EventBus,友盟之类的三方库),依赖其他组件(Service或者Broadcast)等。示例代码如下

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

这样写,看上去,嗯,没毛病,但是在真实的项目中,一个关键的UI组件的生命周期回调方法里,那代码量是相当可观的(onCreate代码分分钟破百行给你看),所以这就使得他们难以维护。

此外,由于我们无法控制生命周期,假如我们在例如onStart中做了一些耗时操作(检查网络状态啊,检查配置文件数据啊,检查数据库啊),如果在这些耗时操作还没执行完,组件就已经完了(onStop或者onDestroy),我们就一脸懵逼了啊(药丸,内存泄漏是小,搞不好会崩),示例代码如下:

class MyActivity extends AppCompatActivity {
    private MyLocationListener myLocationListener;

    public void onCreate(...) {
        myLocationListener = new MyLocationListener(this, location -> {
            // update UI
        });
    }

    @Override
    public void onStart() {
        super.onStart();
        Util.checkUserStatus(result -> {
            // what if this callback is invoked AFTER activity is stopped?
            if (result) {
                myLocationListener.start();
            }
        });
    }

    @Override
    public void onStop() {
        super.onStop();
        myLocationListener.stop();
    }
}

怪我假如太多?哼哼,项目中假如可能比你想象的多。推销进入高潮,那么为了解决以上问题,我们就要用Lifecycle组件。

使用方式

  • 首先在工程根目录的build.gradle中添加一下内容:
allprojects {
    repositories {
        google()
        jcenter()
    }
}
  • 然后在应用目录下的build.gradle中添加以下依赖:
dependencies {
	def lifecycle_version = "2.0.0"
    // alternatively - Lifecycles only (no ViewModel or LiveData).
    // Support library depends on this lightweight import
    compile "android.arch.lifecycle:runtime:$lifecycle_version"
    // ViewModel and LiveData
    compile "android.arch.lifecycle:extensions:$lifecycle_version"
    }
  • 实现LifecycleObserver接口姿势一(如果你使用的是Java7的话):
public class MyObserver7 implements LifecycleObserver {
   @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"); 
    }
}
  • 实现LifecycleObserver接口姿势二(如果你使用的是Java8的话):

注意:如果使用本姿势,你需要支持Java8的组件。

implementation "android.arch.lifecycle:common-java8:1.0.0"
public class MyObserver8 implements DefaultLifecycleObserver {

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

至于原因嘛,官网注释镇楼,自行翻译吧,看情形,Google推荐使用Java8啊:

/ * If you use <b>Java 8 Language</b>, then observe events with {@link DefaultLifecycleObserver}.
 * To include it you should add {@code "android.arch.lifecycle:common-java8:<version>"} to your
 * build.gradle file.
 * <pre>
 * class TestObserver implements DefaultLifecycleObserver {
 *     {@literal @}Override
 *     public void onCreate(LifecycleOwner owner) {
 *         // your code
 *     }
 * }
 * </pre>
 * If you use <b>Java 7 Language</b>, Lifecycle events are observed using annotations.
 * Once Java 8 Language becomes mainstream on Android, annotations will be deprecated, so between
 * {@link DefaultLifecycleObserver} and annotations,
 * you must always prefer {@code DefaultLifecycleObserver}.
 * <pre>
 * class TestObserver implements LifecycleObserver {
 *   {@literal @}OnLifecycleEvent(ON_STOP)
 *   void onStopped() {}
 * }
 * </pre>
 * /
  • 在Activity或Fragment中添加Observer姿势一:
    注意:如果使用本姿势,你需要使用新版本的AppcompatActivity(>26.1.0)。
public class MainActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        // 直接调用getLifecycle(),添加Observer
        getLifecycle().addObserver(new MyObserver7());
        getLifecycle().addObserver(new MyObserver8());
    }
}
  • 在Activity或Fragment中添加Observer姿势二:
    如果你的版本低,那只能自己实现LifecycleOwner接口咯,然后在生命周期回调里分发事件,建议写成Base。
public class BaseActivity 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();
    }
}

至此,Lifecycle基本用法演示完毕,嗯,很方便。

Lifecycle组件成员

Lifecycle:是一个持有UI组件对应生命周期状态信息的类,并允许其他对象观察此类状态。他使用两个主要的枚举来跟踪其关联组件的生命周期。

枚举1:Event:从框架和Lifecycle类派发的生命周期事件。这些事件映射到UI组件中的生命周期回调事件。

枚举2:State:由Lifecycle对象跟踪的组件的当前状态。

Lifecycle将Activity的生命周期函数对应成State,生命周期改变,会造成State改变,而State变化将触发Event事件,从而被LifecycleObser接收。下图是UI组件生命周期变换过程中State和Event关系图:
在这里插入图片描述
LifecycleOwner:Lifecycle持有者,实现该接口的类持有生命周期状态信息的类(Lifecycle对象),生命周期状态信息改变会被其注册的观察者LifecycleObserver观察到并触发其对应的事件。

LifecycleObserver:Lifecycle观察者,实现该接口的类,被注册后,LifecycleObserver便可以观察到Lifecycle的生命周期事件。

源码分析

  • LifecycleOwner是一个接口,里面只有一个接口方法:getLifecycle(),返回值是Lifecycle类型。假设某个类集成了这个接口,实现了getLifecycle()方法,就说明这个类持有了Lifecycle,成为生命周期持有者。
/**
 * A class that has an Android lifecycle. These events can be used by custom components to
 * handle lifecycle changes without implementing any code inside the Activity or the Fragment.
 *
 * @see Lifecycle
 */
@SuppressWarnings({"WeakerAccess", "unused"})
public interface LifecycleOwner {
    /**
     * Returns the Lifecycle of the provider.
     *
     * @return The lifecycle of the provider.
     */
    @NonNull
    Lifecycle getLifecycle();
}
  • LifecycleObserver也是一个接口,里面什么方法也没有。主要是用来标记一个类是一个生命周期观察者,它是通过注解或者继承来实现生命周期的监听。
/**
 * Marks a class as a LifecycleObserver. It does not have any methods, instead, relies on
 * {@link OnLifecycleEvent} annotated methods.
 * <p>
 * @see Lifecycle Lifecycle - for samples and usage patterns.
 */
@SuppressWarnings("WeakerAccess")
public interface LifecycleObserver {

}
  • Lifecycle是一个抽象类,它提供2个重要的抽象方法:添加和删除观察者方法,同时,定义了2个枚举:Event和Status。Lifecycle最重要实现类是LifecycleRegistry类。
    Lifecycle
  • LifecycleRegistry类中维护了一个LifecycleObserver的Map集合,这集合可以支持在遍历的时候进行添加和删除。这个集合规定:后添加的观察者的状态要大于前面添加进去的观察者状态。
    /**
     * Custom list that keeps observers and can handle removals / additions during traversal.
     *
     * Invariant: at any moment of time for observer1 & observer2:
     * if addition_order(observer1) < addition_order(observer2), then
     * state(observer1) >= state(observer2),
     */
    private FastSafeIterableMap<LifecycleObserver, ObserverWithState> mObserverMap =
            new FastSafeIterableMap<>();
  • LifecycleRegistry类中用弱引用保存LifecycleOwner对象,这就保证了,如果LifecycleRegistry类产生了内存泄漏,其持有的LifecycleOwner对象不会被泄漏出去。还是不要随便泄漏任何数据的好~
    /**
     * The provider that owns this Lifecycle.
     * Only WeakReference on LifecycleOwner is kept, so if somebody leaks Lifecycle, they won't leak
     * the whole Fragment / Activity. However, to leak Lifecycle object isn't great idea neither,
     * because it keeps strong references on all other listeners, so you'll leak all of them as
     * well.
     */
    private final WeakReference<LifecycleOwner> mLifecycleOwner;
  • LifecycleRegistry类的构造方法中只有一个参数,那就是接口LifecycleOwner,也就是说,所有实现LifecycleOwner接口的类,都能用于创建LifecycleRegistry,也就是Lifecycle。
    /**
     * Creates a new LifecycleRegistry for the given provider.
     * <p>
     * You should usually create this inside your LifecycleOwner class's constructor and hold
     * onto the same instance.
     *
     * @param provider The owner LifecycleOwner
     */
    public LifecycleRegistry(@NonNull LifecycleOwner provider) {
        mLifecycleOwner = new WeakReference<>(provider);
        mState = INITIALIZED;
    }
  • LifecycleRegistry也实现了添加和删除观察者的具体逻辑,简单的说,就是对这个Map集合进行添加和删除操作。
    添加时putIfAbsent()方法表示,如果被添加的元素存在,就返回该元素,否则返回null。所以当previous值为空才表示添加成功。并将之前的状态分发给这个Observer,例如我们在onResume之后注册这个Observer,该Observer依然能收到ON_CREATE事件。
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);
        }
        ......
    }

删除时就很简单了

    @Override
    public void removeObserver(@NonNull LifecycleObserver observer) {
        // we consciously decided not to send destruction events here in opposition to addObserver.
        // Our reasons for that:
        // 1. These events haven't yet happened at all. In contrast to events in addObservers, that
        // actually occurred but earlier.
        // 2. There are cases when removeObserver happens as a consequence of some kind of fatal
        // event. If removeObserver method sends destruction events, then a clean up routine becomes
        // more cumbersome. More specific example of that is: your LifecycleObserver listens for
        // a web connection, in the usual routine in OnStop method you report to a server that a
        // session has just ended and you close the connection. Now let's assume now that you
        // lost an internet and as a result you removed this observer. If you get destruction
        // events in removeObserver, you should have a special case in your onStop method that
        // checks if your web connection died and you shouldn't try to report anything to a server.
        mObserverMap.remove(observer);
    }
  • LifecycleRegistry类中有一个重要的方法handleLifecycleEvent(),这个方法的参数是Lifecycle.Event,用于向Map集合中的观察者发送被观察者生命周期改变的通知。其中通过sync()方法同步Observer状态,并分发事件。handleLifecycleEvent()方法最终通过调用forwardPass()和backwordPass()方法遍历Map集合通知观察者。
	/**
     * 处理生命周期事件
     */
    public void handleLifecycleEvent(@NonNull Lifecycle.Event event) {
        State next = getStateAfter(event);
        moveToState(next);
    }

    /**
     * 改变状态
     */
    private void moveToState(State next) {
        if (mState == next) {
            return;
        }
        mState = next;
        ......
        sync();
        ......
    }

    /**
     * 同步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();
            }
        }
    }
}
  • ObserverWithState是LifecycleRegistry类的一个静态内部类,这个类用于保存观察者的状态,同时,图中我们看到,事件最后是调用这个类的dispatchEvent()方法来分发的。而这个方法中最终调用的是继承了LifecycleObserver接口的一个新接口GenericLifecycleOberver中的方法onStateChanged();
    ObserverWithState
    GenericLifecycleOberver
  • 然而GenericLifecycleObserver是隐藏的,我们用不了,所以我们通过上文中提到两种姿势实现。在这里,我们又懵逼的发现,只调用了一个onStateChanged()方法,但是上文中的两个姿势里可是写了一堆的方法啊,单从数目上看,这不匹配。入口在这里:
	mLifecycleObserver = Lifecycling.getCallback(observer);
  • 看下getCallback()方法:
static GenericLifecycleObserver getCallback(Object object) {
        if (object instanceof FullLifecycleObserver) {
            return new FullLifecycleObserverAdapter((FullLifecycleObserver) object);
        }

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

嗯,上文中提到的第二个实现LifecycleObserver的姿势用的是DefaultLifecycleObserver,这个接口正好是继承FullLifecycleObserver的,所以,我再看下FullLifecycleObserverAdapter干了啥:

class FullLifecycleObserverAdapter implements GenericLifecycleObserver {

    private final FullLifecycleObserver mObserver;

    FullLifecycleObserverAdapter(FullLifecycleObserver observer) {
        mObserver = observer;
    }

    @Override
    public void onStateChanged(LifecycleOwner source, Lifecycle.Event event) {
        switch (event) {
            case ON_CREATE:
                mObserver.onCreate(source);
                break;
            case ON_START:
                mObserver.onStart(source);
                break;
            case ON_RESUME:
                mObserver.onResume(source);
                break;
            case ON_PAUSE:
                mObserver.onPause(source);
                break;
            case ON_STOP:
                mObserver.onStop(source);
                break;
            case ON_DESTROY:
                mObserver.onDestroy(source);
                break;
            case ON_ANY:
                throw new IllegalArgumentException("ON_ANY must not been send by anybody");
        }
    }
}

嗯,代码很简答,这样,整体就通了啊,数目对上了~哈哈哈

  • Support Library 26.1.0 及其以后的版本,Activity 和Fragment 已经实现了LifecycleOwner接口,所以,我们可以直接在Activity和Fragment中使用getLifecycle()方法来获取Lifecycle对象,来添加观察者监听。下图中可以看到,源码中直接在Fragment或Activity中直接创建了一个LifecycleRegistry类的实例,由于Fragment或Activity实现了LifecycleOwner接口,所以可以直接使用this关键字将自身作为参数。一般我们会用带有生命周期的类来实现LifecycleOwner接口。
    在这里插入图片描述

  • Fragment持有LifecycleRegistry类的实例后,实际上在Fragment对应的生命周期内,都会发送对应的生命周期事件给内部的LifecycleRegistry对象处理:
    Fragment持有LifecycleRegistry类

  • 看源码我们会发现,在Activity的performXXX()类似方法中,没有找到mLifecycleRegistry.handleLifecycleEvent()方法的调用。其实新版本的AppCompatActivity最终也是通过调用Fragment中的这些方法来发送通知的,我们来看一下(AppCompatActivity继承自SupportActivity):

public class SupportActivity extends Activity implements LifecycleOwner {
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ReportFragment.injectIfNeededIn(this);
    }
}

嗯,有点意思,我们再看下ReportFragment干了啥:

public class ReportFragment extends Fragment {

    public static void injectIfNeededIn(Activity activity) {
        android.app.FragmentManager manager = activity.getFragmentManager();
        if (manager.findFragmentByTag(REPORT_FRAGMENT_TAG) == null) {
            manager.beginTransaction().add(new ReportFragment(), REPORT_FRAGMENT_TAG).commit();
            manager.executePendingTransactions();
        }
    }

    @Override
    public void onStart() {
        super.onStart();
        dispatchStart(mProcessListener);
        dispatch(Lifecycle.Event.ON_START);
    }

    // ...... 其他生命周期也是同样调用了dispatch(Lifecycle.Event.xxx)分发事件

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

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

所以,Android藏了一手啊,添加了一个没有页面的Fragment来完成Activity的生命周期事件的分发。

  • 为什么不直接在SupportActivity的生命周期函数中给Lifecycle分发生命周期事件,而是要加一个Fragment呢?
    因为不是所有的页面都继承AppCompatActivity,为了兼容非AppCompatActivity,所以封装一个同样具有生命周期的Fragment来给Lifecycle分发生命周期事件。

  • 找了一位大神的总结图:

在这里插入图片描述

最佳实践(官网提供)

  • 尽可能保持UI组件(Activity和Fragment)精简。他们不应该试图获取数据,使用ViewModel来完成这项工作,并观察LiveData对象来及时更新UI。
  • 尝试编写数据驱动的用户界面,其中您的用户界面控制器的职责是在数据更改时更新视图,或将用户操作通知给ViewModel。
  • 把你的数据逻辑放在ViewModel类中。ViewModel应作为您的UI控制器和其他应用程序之间的连接器。但要小心,ViewModel不负责提取数据(例如,来自网络)。相反,ViewModel应调用相应的组件来获取数据,然后将结果提供给UI控制器。
  • 使用dataBinding在视图和UI控制器之间保持干净的界面。这使您可以使您的视图更具说明性,并最大限度地减少需要在UI组件中编写的更新代码。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值