文章目录

  • 一、概念
  • 二、使用
  • 2.1 添加依赖:
  • 2.2 实现LifecycleObserver接口
  • 2.2.1 Java1.7使用LifecycleObserver
  • 2.2.2 Java1.8使用DefaultLifecycleObserver
  • 2.3 将LifecycleObserver添加到Lifecycle的观察者列表
  • 三、优势场景举例
  • 3.1 自定义生命周期函数+自己调用转发
  • 3.2 使用Lifecycle
  • 四、源码解析
  • 4.1 State状态 和 Event事件
  • 4.2 Activity/Fragment的生命周期触发state的改变
  • 4.2.1 从AppCompatActivity的getLifecycle()开始
  • 4.2.1.1 Activity基于ReportFragment将事件传递给LifecycleRegistry
  • 4.2.1.2 为什么不直接在SupportActivity的生命周期函数中给Lifecycle分发生命周期事件,而是要加一个Fragment呢?
  • 4.2.2 LifecycleDispatcher生命周期分发者
  • 4.3 Event事件分发到LifecycleObserver
  • 五、ProcessLifecycleOwner进程启动生命周期
  • 5.1 ProcessLifecycleOwner和LifecycleDispatcher两个类是在哪里初始化呢?
  • 参考文献


一、概念

众所周知,Android凡是需要展示给用户看的,都包含着生命周期这个概念,例如Activity、Fragment、View等都与生命周期息息相关,在生命周期函数里,它们各自完成创建、渲染、销毁等工作。

但是一旦我们往某个生命周期函数中,加入我们自己的逻辑,若是处理不当,就有可能破坏其原有的生命周期,造成内存泄漏甚至应用崩溃等问题。

Android官方似乎也注意到了这一点,因此在Google IO 2018大会上,推出了Android Jetpack开发工具包,其中就包含了一个非常重要的生命周期组件,即本篇的主角-Lifecycle

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

Lifecycle已经纳入新版本的AppCompatActivity和Fragment中了,并且Lifecycle还是Android Jetpack中其他两个组件LiveData和ViewModel的基础

二、使用

2.1 添加依赖:

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

dependencies {
    ......
    implementation "android.arch.lifecycle:runtime:1.1.1"
    implementation "android.arch.lifecycle:extensions:1.1.1"
    // 如果你使用java8开发,可以添加这个依赖,里面只有一个类
    implementation "android.arch.lifecycle:common-java8:1.1.1"
}

2.2 实现LifecycleObserver接口

2.2.1 Java1.7使用LifecycleObserver

public class Java7Observer 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"); }
}
  1. 我们需要实现LifecycleObserver这个接口
  2. 然后在我们的方法上加上@OnLifecycleEvent注解,注解值表示该方法对应生命周期的哪个函数
  1. 这里我们把所有生命周期函数都加上了,并简单地打印了一句Log

2.2.2 Java1.8使用DefaultLifecycleObserver

public class Java8Observer 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"); }
}

理由很简单,Lifecycle源码中有一段注释:

  • If you use Java 7 Language, 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}.

翻译一下就是:“如果你丫的用的是java7,那你就用注解呗,但是我告诉你,一旦java8上位了,你那些注解就过时了,我劝你最好用DefaultLifecycleObserver”

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

  • 如果你使用新版本的AppcompatActivity(>26.1.0),那么可以直接调用getLifecycle(),添加Observer,可以这么写:
public class MainActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        // 直接调用getLifecycle(),添加Observer
        getLifecycle().addObserver(new Java7Observer());
        getLifecycle().addObserver(new Java8Observer());
    }
}
  • 如果你的AppCompatActivity没有更新到最新,那么你需要自实现LifecycleOwner接口,并在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();
    }
}

ok,完事儿了,咱们跑起来看一哈,已经成功和生命周期关联上了。

android ProcessLifecycleOwner好用吗 android lifecycle是做什么的_ide

三、优势场景举例

举个熟悉点的例子

MVP想必大家都用过,或者听说过,View层通过Presenter层和Model层进行通信,因此Presenter层如果做了什么超出View生命周期的事,又没有及时释放内存,就会造成内存泄漏。

所以,原来的Presenter,为了响应生命周期,我们可能会这么写:

3.1 自定义生命周期函数+自己调用转发

先定义所有的生命周期函数

public class MainPresenter {
    public void onCreate() { }
    public void onStart() { }
    public void onResume() { }
    public void onPause() { }
    public void onStop() { }
    public void onDestroy() { }
}

然后再与Activity生命周期一一绑定,如果有多个类似的需要响应生命周期的类,Activity的生命周期函数就会变得非常臃肿

public class MainActivity extends AppCompatActivity {
    private MainPresenter mPresenter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mPresenter = new MainPresenter();
        mPresenter.onCreate();
    }

    @Override
    protected void onResume() {
        super.onResume();
        mPresenter.onCreate();
        // VideoPlayer.onResume();
        // ...
    }

    @Override
    protected void onStart() {
        super.onStart();
        mPresenter.onStart();
        // VideoPlayer.onStart();
        // ...
    }

    @Override
    protected void onPause() {
        super.onPause();
        mPresenter.onPause();
        // VideoPlayer.onPause();
        // ...
    }

    @Override
    protected void onStop() {
        super.onStop();
        mPresenter.onStop();
        // VideoPlayer.onStop();
        // ...
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mPresenter.onDestroy();
        // VideoPlayer.onDestroy();
        // ...
    }
}

3.2 使用Lifecycle

因此,Lifecycle就是为了解决这个痛点,将生命周期的响应分发到各个观察者中去,我们只需要在Activity中调用一行代码:

getLifecycle().addObserver(mPresenter);

代码量蹭蹭就下来了。诸如音视频播放、图片加载,这些吃内存大户,都应该响应生命周期,及时释放内存,否则很可能就会造成OOM。

四、源码解析

在项目中引入一个库,却不懂是怎么实现的,是一件非常危险的行为,因此我们不仅要学会怎么用,还得知道其中的原理。

4.1 State状态 和 Event事件

先看一张官方的图:

android ProcessLifecycleOwner好用吗 android lifecycle是做什么的_Android_02


可以看到两个很显眼的单词:State和Event,这也是贯穿整个Lifecycle的两个概念:状态和事件。

Lifecycle将Activity的生命周期函数对应成State,生命周期改变,会造成State改变,而State变化将触发Event事件,从而被LifecycleObser接收。

  • State:状态,是Lifecycle中对应Activity生命周期的一种状态标识
  • INITIALIZED:对应Activity的onCreate之前的生命周期
  • CREATED:对应Activity的onCreate到onStop之间的生命周期
  • STARTED:对应Activity的onStart到onPause之间的生命周期
  • RESUMED:对应Activity的onResume
  • DESTROYED:对应Activity的onDestroy
  • Event:事件,当State发生变化时,Lifecycle会向已注册的LifecycleObserver发送事件
  • 例如:当State从INITIALIZED变化到CREATED时,就会发出ON_CREATE事件。

需要注意,没有定义STOPED 和 PAUSED, 这其实在上图上也能看出来,我们只定义了5种状态,从低到高的传递其实会引发oncreate\onstart\onresume触发,从高到底的传递就是onpause\onstop的过程。
这样子设计的原因,也是方便对应的LifeOwner的状态能在销毁时自动重置

因此,弄懂Lifecycle,其实也就是需要弄懂两件事:

  1. Activity/Fragment的生命周期如何触发state的改变?
  1. 如果你的Activity继承AppCompatActivity
  1. 在Activity中添加一个ReportFragment(会在父类的onCreate()中添加ReportFragment)
  2. 在ReportFragment生命周期函数中调用getActivity().getLifecycleRegistry().handleLifecycleEvent()方法改变State。
  1. 否则由LifecycleDispatcher添加
  1. 通过注册Application.registerActivityLifecycleCallbacks来监听Activity的生命周期回调的
  2. 在onActivityCreated()中添加ReportFragment,将Activity的生命周期交给ReportFragment去分发给LifecycleRegistry
  3. ReportFragment会自动触发Activity容器的事件转发getActivity().getLifecycleRegistry().handleLifecycleEvent()
  1. Event事件是如何分发到LifecycleObserver的?
  1. LifecycleRegistry在收到handleLifecycleEvent()后,内部调用moveToState()方法,改变State值
  2. 每一次State值改变,都会调用LifecycleObserver.onStateChanged()方法将Event分发到LifecycleObserver

4.2 Activity/Fragment的生命周期触发state的改变

4.2.1 从AppCompatActivity的getLifecycle()开始

  • 由于AppCompatActivity继承自SupportActivity,我们发现,AppCompatActivity.getLifecycle(),最终定位在了SupportActivity.getLifecycle()方法中
public class SupportActivity extends Activity implements LifecycleOwner {
    ......

    private LifecycleRegistry mLifecycleRegistry = new LifecycleRegistry(this);

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

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

    ......
}

public interface LifecycleOwner {
    /**
     * Returns the Lifecycle of the provider.
     *
     * @return The lifecycle of the provider.
     */
    @NonNull
    Lifecycle getLifecycle();
}
  1. SupportActivity实现了LifecycleOwner接口,其抽象行为就是getLifecycle()
  • getLifecycle()返回了一个LifecycleRegistry 对象,所以所有对LifecycleObserver的操作都是由LifecycleRegistry 完成的
  1. 在onCreate()方法中,我们还看到了一个ReportFragment.injectIfNeededIn(this),这个就是用于做事件转发的。
4.2.1.1 Activity基于ReportFragment将事件传递给LifecycleRegistry
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);
            }
        }
    }
}

SupportActivity添加了一个没有页面的ReportFragment,在ReportFragment的生命周期函数中,调用了LifecycleRegistry.handleLifecycleEvent()方法来分发生命周期事件。

android ProcessLifecycleOwner好用吗 android lifecycle是做什么的_ide_03

4.2.1.2 为什么不直接在SupportActivity的生命周期函数中给Lifecycle分发生命周期事件,而是要加一个Fragment呢?

因为不是所有的页面都继承AppCompatActivity,为了兼容非AppCompatActivity,所以封装一个同样具有生命周期的Fragment来给Lifecycle分发生命周期事件。

那么,如果我们不继承新版本AppCompatActivity时,Lifecycle是如何通过ReportFragment来分发生命周期事件的呢?

这里我们直接使用AndroidStudio强大的搜索功能,alt+F7搜索ReportFragment的调用者,我们发现:除了SupportActivity以外,还有两个地方使用到了ReportFragment:LifecycleDispatcher和ProcessLifecycleOwner

4.2.2 LifecycleDispatcher生命周期分发者

  • LifecycleDispatcher是通过注册Application.registerActivityLifecycleCallbacks来监听Activity的生命周期回调的
  • 在onActivityCreated()中添加ReportFragment,将Activity的生命周期交给ReportFragment去分发给LifecycleRegistry
  • ReportFragment会自动触发Activity容器的事件转发(只要activity有LifecycleRegistry)
  • 在onActivityStopped()以及onActivitySaveInstanceState()中,将Activity及其所有子Fragment的State置为CREATED
class LifecycleDispatcher {
    static void init(Context context) {
        ((Application) context.getApplicationContext())
            .registerActivityLifecycleCallbacks(new DispatcherActivityCallback());
    }

    // 通过注册Application.registerActivityLifecycleCallbacks来获取Activity的生命周期回调
    static class DispatcherActivityCallback extends EmptyActivityLifecycleCallbacks {
            @Override
            public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
                if (activity instanceof FragmentActivity) {
                    ((FragmentActivity) activity).getSupportFragmentManager()
                            .registerFragmentLifecycleCallbacks(mFragmentCallback, true);
                }
                // 给每个Activity添加ReportFragment
                ReportFragment.injectIfNeededIn(activity);
            }

            @Override
            public void onActivityStopped(Activity activity) {
                if (activity instanceof FragmentActivity) {
                    markState((FragmentActivity) activity, CREATED);
                }
            }

            @Override
            public void onActivitySaveInstanceState(Activity activity, Bundle outState) {
                if (activity instanceof FragmentActivity) {
                    markState((FragmentActivity) activity, CREATED);
                }
            }
        }

    /**
     * 给所有子Fragment设置State
     */
    private static void markState(FragmentManager manager, State state) {
        Collection<Fragment> fragments = manager.getFragments();
        if (fragments == null) {
            return;
        }
        for (Fragment fragment : fragments) {
            if (fragment == null) {
                continue;
            }
            markStateIn(fragment, state);
            if (fragment.isAdded()) {
                markState(fragment.getChildFragmentManager(), state);
            }
        }
    }

    private static void markStateIn(Object object, State state) {
        if (object instanceof LifecycleRegistryOwner) {
            LifecycleRegistry registry = ((LifecycleRegistryOwner) object).getLifecycle();
            registry.markState(state);
        }
    }
}

4.3 Event事件分发到LifecycleObserver

上文提及了一个核心管理类:LifecycleRegistry生命周期登记处

这个类是Lifecycle中最重要的一个类,它是Lifecycle的子类,起着:

  1. 添加、删除观察者;
  2. 响应生命周期事件;
  3. 分发生命周期事件的作用;
public class LifecycleRegistry extends Lifecycle {
    // LifecycleObserver Map,每一个Observer都有一个State
    private FastSafeIterableMap<LifecycleObserver, ObserverWithState> mObserverMap = new FastSafeIterableMap<>();
    // 当前的状态
    private State mState;
    // 生命周期拥有者,上述的SupportActivity继承了LifecycleOwner
    private final WeakReference<LifecycleOwner> mLifecycleOwner;

    public LifecycleRegistry(@NonNull LifecycleOwner provider) {
        mLifecycleOwner = new WeakReference<>(provider);
        mState = INITIALIZED;
    }

    /**
    * 一、添加LifecycleObserver观察者,并将之前的状态分发给这个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);
        }
        ......
    }

    /**
     * 二、处理生命周期事件
     */
    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();
            }
        }
    }
}

android ProcessLifecycleOwner好用吗 android lifecycle是做什么的_ide_04

  1. LifecycleRegistry添加观察者
  2. AppCompatActivity中添加了一个ReportFragment,其生命周期变化时,调用LifecycleRegistry.handleLifecycleEvent()方法通知LifecycleRegistry改变状态
  1. LifecycleRegistry内部调用moveToState()改变状态
  2. 并调用每个LifecycleObserver.onStateChange()方法通知生命周期变化

五、ProcessLifecycleOwner进程启动生命周期

  • ProcessLifecycleOwner是用来监听Application生命周期的,因此它只会分发一次ON_CREATE事件,并且不会分发ON_DESTROY事件。
  1. ProcessLifecycleOwner在Activity的onResume和onStop方法中都采用了Handle.postDelayed()方法,是为了处理Activity重建时比如横竖屏幕切换时,不会发送事件。
  2. ProcessLifecycleOwner一般用来判断应用是在前台还是后台。但由于使用了Handle.postDelayed(),因此这个判断不是即时的,有默认700ms的延迟。
  3. ProcessLifecycleOwner与LifecycleDispatcher一样,都是通过注册Application.registerActivityLifecycleCallbacks来监听Activity的生命周期回调,来给每个Activity添加ReportFragment的。
public class ProcessLifecycleOwner implements LifecycleOwner {
    public static LifecycleOwner get() { return sInstance; }

    static void init(Context context) {
        sInstance.attach(context);
    }
    
    void attach(Context context) {
        mHandler = new Handler();
        mRegistry.handleLifecycleEvent(Lifecycle.Event.ON_CREATE);
        Application app = (Application) context.getApplicationContext();
        app.registerActivityLifecycleCallbacks(new EmptyActivityLifecycleCallbacks() {
            @Override
            public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
                ReportFragment.get(activity).setProcessListener(mInitializationListener);
            }

            @Override
            public void onActivityPaused(Activity activity) {
                activityPaused();
            }

            @Override
            public void onActivityStopped(Activity activity) {
                activityStopped();
            }
        });
    }

    void activityResumed() {
        mResumedCounter++;
        if (mResumedCounter == 1) {
            if (mPauseSent) {
                mRegistry.handleLifecycleEvent(Lifecycle.Event.ON_RESUME);
                mPauseSent = false;
            } else {
                mHandler.removeCallbacks(mDelayedPauseRunnable);
            }
        }
    }

    void activityPaused() {
        mResumedCounter--;
        if (mResumedCounter == 0) {
            mHandler.postDelayed(mDelayedPauseRunnable, TIMEOUT_MS);
        }
    }

    private ActivityInitializationListener mInitializationListener = new ActivityInitializationListener() {
        @Override
        public void onCreate() {}

        @Override
        public void onStart() {
            activityStarted();
        }

        @Override
        public void onResume() {
            activityResumed();
        }
    };

   
}

5.1 ProcessLifecycleOwner和LifecycleDispatcher两个类是在哪里初始化呢?

  • 业界常用做法,使用ContentProvider的初始化,在Application.attach时就会触发

Lifecycle自动在我们的AndroidManifest.xml中添加了一个ContentProvider,用于初始化ProcessLifecycleOwner和LifecycleDispatcher,这么做的好处是,不需要我们在Application中显示调用,不需要我们写一行代码。

public class ProcessLifecycleOwnerInitializer extends ContentProvider {
    @Override
    public boolean onCreate() {
        LifecycleDispatcher.init(getContext());
        ProcessLifecycleOwner.init(getContext());
        return true;
    }
    // ......
}


AndroidManifest.xml
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
  ......
  <provider
    android:name="android.arch.lifecycle.ProcessLifecycleOwnerInitializer"
    android:authorities="me.baron.achitecturelearning.lifecycle-trojan"
    android:exported="false"
    android:multiprocess="true" />
</manifest>

参考文献