目录
问题
在使用Android Architecture Component的时候,Lifecycle的存在感是最低的,因为AppCompat包已经帮我们实现了Activity和Fragment的Lifecycle。Lifecycle最主要的作用是抽象生命周期,让包括LiveData在内的观察者实现对生命周期的感知。关于Lifecycle,我能想到如下一些问题:
- 什么是Lifecycle?
- 怎样以无侵入的方式实现Lifecycle?
- 我们经常使用Activity和Fragment的Lifecycle,按道理说,Application也有Lifecycle,该怎么实现它的Lifecycle?
带着这些问题,去源码中找寻答案。(源码版本androidx.lifecycle:lifecycle-runtime:2.2.0
)
1. Lifecycle概览
Lifecycle is a class that holds the information about the lifecycle state of a component (like an activity or a fragment) and allows other objects to observe this state.
Lifecycle是一个持有组件生命周期状态的类,它允许其它类来观察这种的状态。说白了就是让Activity、Fragment之类的生命周期状态“转移”到Lifecycle类中,因此我们就可以通过Lifecycle类去观察生命周期,完成相应的行为。
但是,为什么要这么做呢?在Activity或者Fragment生命周期函数中完成我们想要的行为不也一样吗?
首先,使用Lifecycle一个显而易见的好处就是解耦。假设我们需要在Activity的onStart
方法中去触发十个八个行为,并且在onStop
方法中去停止这些行为,如果把这些代码都堆在Activity的生命周期的方法中,显然是非常丑陋的。使用Lifecycle,我们可以为每一个行为定义一个观察者类,再让这十个八个观察者类去观察Lifecycle,这样代码结构会清晰很多,并且也更加符合单一职责原则。
其次,使用Lifecycle可以更加方便地处理一些生命周期状态和用户状态相互影响的情况。Google文档中给出了一个例子。
最后,Lifecycle的抽象给LiveData的实现提供了便利。
2. 什么是Lifecycle
/**
* Lifecycle的注释中有两个重要信息:
* 1. ON_CREATE, ON_START, ON_RESUME 事件是在 LifecycleOwner 相应方法之后才发出的.
* ON_PAUSE, ON_STOP, ON_DESTROY 事件是在 LifecycleOwner 相应方法之前就发出的.
* 这是为了保证 LifecycleOwner 的确切状态。
* 2. 相较于使用 OnLifecycleEvent 注解的方式去定义 LifecycleObserver,
* 你应该更加倾向于使用 DefaultLifecycleObserver(包含在 androidx.lifecycle:common-java8 中)
* 在Java 8成为Android主流之后,使用注解的方式就会被废弃。
*/
public abstract class Lifecycle {
/**
* 添加观察者
* Adds a LifecycleObserver that will be notified when the LifecycleOwner changes
* state.
*/
@MainThread
public abstract void addObserver(@NonNull LifecycleObserver observer);
/**
* 移除观察者
* Removes the given observer from the observers list.
* <p>
* If this method is called while a state change is being dispatched,
* <ul>
* <li>If the given observer has not yet received that event, it will not receive it.
* <li>If the given observer has more than 1 method that observes the currently dispatched
* event and at least one of them received the event, all of them will receive the event and
* the removal will happen afterwards.
* </ul>
*/
@MainThread
public abstract void removeObserver(@NonNull LifecycleObserver observer);
@MainThread
@NonNull
public abstract State getCurrentState();
}
/**
* LifecycleObserver只是一个标记接口,没有方法
* 可以使用 OnLifecycleEvent 注解去定义 LifecycleObserver
* 但是,如前所述,更应该使用 Java 8 的 DefaultLifecycleObserver 去实现
*/
public interface LifecycleObserver {
}
/**
* 与 Lifecycle有关的 LifecycleOwner接口
*/
public interface LifecycleOwner {
@NonNull
Lifecycle getLifecycle();
}
Lifecycle就是这么简单,总结起来就是:一、有状态;二、可以增删观察者。另外Lifecycle类中还定义了State和Event:
public abstract class Lifecycle {
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;
}
}
}
State和Event的关系如图所示:
LifecycleOwner,Lifecycle,LifecycleObserver关系如图所示:
图片来源https://blog.kyleduo.com/2019/01/17/lifecycle-source-code/
3. Activity和Fragment如何实现Lifecycle
AppCompat包从26.1.0开始,就已经帮我们在Activity和Fragment中实现了LifecycleOwner接口。androidx包下的Activity和Fragment自然就更不用说了。
3.1 Activity如何实现Lifecycle
尽管我们使用了AppCompat包,但是并不能保证应用中所有的Activity一定继承自AppCompatActivity(例如,使用的第三方库中的Activity没有继承自AppCompatActivity),因此就不能直接在AppCompatActivity或者其某个基类的生命周期方法中去实现Lifecycle。Google的做法是向Activity中添加一个看不见的Fragment,名为ReportFragment,专门向Activity“报告”当前的生命周期,这样就保证了所有Activity的生命周期都会通过ReportFragment被“报告”。由于不能确定Activity的具体类型,因此ReportFragment必须继承自android.app.Fragment,不能使用兼容包下的Fragment。
按理说,对于没有继承自兼容包的Activity,是完全有理由放弃为其实现Lifecycle的,因为即使使用了ReportFragment,也仅仅保证了Activity的生命周期被正常的“报告”,这个Activity并没有实现LifecycleOwner接口,这导致ReportFragment的“报告”没有办法被获取,因此,使用ReportFragment并不是为了让所有的Activity都实现Lifecycle。其实,这么做是为了让Application能正确的实现Lifecycle,这一点后面的源码中会有体现。
/**
* AppCompatActivity的基类,实现了LifecycleOwner接口
*/
public class ComponentActivity implements LifecycleOwner {
private final LifecycleRegistry mLifecycleRegistry = new LifecycleRegistry(this);
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//injectIfNeededIn 如果需要就注入
ReportFragment.injectIfNeededIn(this);
}
@NonNull
@Override
public Lifecycle getLifecycle() {
return mLifecycleRegistry;
}
}
LifecycleOwner的实现非常简单,把一切都交给了LifecycleRegistry,看来LifecycleRegistry才是关键。LifecycleRegistry是实现Lifecycle的关键,待我们把相关的源码看完之后,再回过头来看LifecycleRegistry。
ReportFragment在onCreate方法中被添加到Activity中,并且是通过ReportFragment的静态方法injectIfNeededIn
,需要才添加。那还有不需要的时候吗?前面说了,你的Activity并不一定会继承自这个ComponentActivity,如果Activity不继承自这个ComponentActivity,ReportFragment依然会被添加,只是不是通过这里被添加的(后文会讲到),为了防止Activity重复添加ReportFragment,因此ReportFragment实现了静态方法injectIfNeededIn
。好吧,来瞄一眼ReportFragment吧。
//继承自android.app.Fragment
public class ReportFragment extends Fragment {
private static final String REPORT_FRAGMENT_TAG = "androidx.lifecycle"
+ ".LifecycleDispatcher.report_fragment_tag";
//如果没有添加过ReportFragment才进行添加
public static void injectIfNeededIn(Activity activity) {
if (Build.VERSION.SDK_INT >= 29) {
// API 29+ 流程略有不同,并不影响主流程,可以忽略
activity.registerActivityLifecycleCallbacks(
new LifecycleCallbacks());
}
//不使用兼容包下的FragmentManager
android.app.FragmentManager manager = activity.getFragmentManager();
if (manager.findFragmentByTag(REPORT_FRAGMENT_TAG) == null) {
manager.beginTransaction().add(new ReportFragment(), REPORT_FRAGMENT_TAG).commit();
manager.executePendingTransactions();
}
}
static ReportFragment get(Activity activity) {
return (ReportFragment) activity.getFragmentManager().findFragmentByTag(
REPORT_FRAGMENT_TAG);
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
dispatch(Lifecycle.Event.ON_CREATE);
}
@Override
public void onStart() {
super.onStart();
dispatch(Lifecycle.Event.ON_START);
}
@Override
public void onResume() {
super.onResume();
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);
}
private void dispatch(Lifecycle.Event event) {
dispatch(getActivity(), event);
}
static void dispatch(@NonNull Activity activity, @NonNull Lifecycle.Event event) {
if (activity instanceof LifecycleOwner) {
Lifecycle lifecycle = ((LifecycleOwner) activity).getLifecycle();
if (lifecycle instanceof LifecycleRegistry) {
((LifecycleRegistry) lifecycle).handleLifecycleEvent(event);
}
}
}
}
ReportFragment的职责非常简单,在对应的生命周期中分发对应的事件给Activity的LifecycleRegistry。
Lifecycle的注释中提到
ON_CREATE, ON_START, ON_RESUME 事件是在 LifecycleOwner 相应方法之后才发出的.
ON_PAUSE, ON_STOP, ON_DESTROY 事件是在 LifecycleOwner 相应方法之前就发出的.
头一句没有问题,第二句话似乎跟代码不符,ReportFragment明明是在onPause
,onStop
,onDestroy
方法之后才分发的对应的事件。但是别忘了,ReportFragment是为了监听Activity的生命周期,ReportFragment的onPause
,onStop
,onDestroy
确实是在Activity对应方法之前被调用的,因为ReportFragment是android.app.Fragment,如果是兼容包的Fragment,其onPause
,onStop
,onDestroy
是在Activity对应方法之后被调用,我也是刚刚发现。
总结一下,Activity是如何实现Lifecycle的。ReportFragment被添加到Activity中,并在ReportFragment相应的生命周期方法中,通知Activity的LifecycleRegistry相应的事件。
3.2 Fragment如何实现Lifecycle
从Android P开始,android.app.Fragment已经被标记为废弃的,显然Google已经不推荐我们使用“原生”的Fragment,相反,我们应该使用兼容包中的Fragment。android.app.Fragment也没有实现Lifecycle,我们只需要看兼容包中的Fragment是如何实现Lifecycle的即可。
//androidx.fragment.app.Fragment
public class Fragment implements LifecycleOwner {
LifecycleRegistry mLifecycleRegistry;
@Override
@NonNull
public Lifecycle getLifecycle() {
return mLifecycleRegistry;
}
public Fragment() {
initLifecycle();
}
private void initLifecycle() {
mLifecycleRegistry = new LifecycleRegistry(this);
//...
}
/**
* 先调用Fragment的onCreate,然后发送ON_CREATE事件
*/
void performCreate(Bundle savedInstanceState) {
//...
onCreate(savedInstanceState);
mLifecycleRegistry.handleLifecycleEvent(Lifecycle.Event.ON_CREATE);
//...
}
/**
* 先发送ON_DESTROY事件,然后调用Fragment的onDestroy
*/
void performDestroy() {
//...
mLifecycleRegistry.handleLifecycleEvent(Lifecycle.Event.ON_DESTROY);
onDestroy();
//...
}
//其它生命周期类似,不再列出
}
比Activity还要简单,直接在相应的生命周期中通知LifecycleRegistry即可。并且Fragment的源码再次印证了Lifecycle注释中的那句话:
ON_CREATE, ON_START, ON_RESUME 事件是在 LifecycleOwner 相应方法之后才发出的.
ON_PAUSE, ON_STOP, ON_DESTROY 事件是在 LifecycleOwner 相应方法之前就发出的.
通过分析Activity和Fragment中的源码可以看出,Lifecycle真正的实现是在LifecycleRegistry中。
4. Lifecycle的本尊LifecycleRegistry
兜兜转转还得回到LifecycleRegistry。在分析LifecycleRegistry源码之前,先明确一下LifecycleRegistry的职责:
- 持有生命周期的状态。
- 接收生命周期事件,完成在生命周期状态之间的跳转。
- 可以添加多个观察者,并且可以随时移除观察者。
- 向多个观察者传递生命周期事件,维护多个观察者的生命周期状态。
以上职责大致分为两部分:第一,观察者的添加和移除;第二,生命周期状态的管理,包括LifecycleRegistry本身的生命周期状态和观察者的生命周期状态(注意区分两者)。
4.1 LifecycleRegistry观察者的添加和移除
public class LifecycleRegistry extends Lifecycle {
/**
* 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)
*
* 以上这段话非常重要,先添加的观察者observer1的状态state1,永远要比
* 后添加的观察者observer2的状态state2大,即state1 >= state2
* 或者表达为state(observer1) >= state(observer2)
* 这被称为“不变性”
*/
private FastSafeIterableMap<LifecycleObserver, ObserverWithState> mObserverMap =
new FastSafeIterableMap<>();
/**
* 当前的 state
*/
private State mState;
private final WeakReference<LifecycleOwner> mLifecycleOwner;
//记录是否正在添加观察者
private int mAddingObserverCounter = 0;
private boolean mHandlingEvent = false;
private boolean mNewEventOccurred = false;
// we have to keep it for cases:
// void onStart() {
// mRegistry.removeObserver(this);
// mRegistry.add(newObserver);
// }
// newObserver should be brought only to CREATED state during the execution of
// this onStart method. our invariant with mObserverMap doesn't help, because parent observer
// is no longer in the map.
// 举了一个例子来说明 parentStates的作用
private ArrayList<State> mParentStates = new ArrayList<>();
public LifecycleRegistry(@NonNull LifecycleOwner provider) {
mLifecycleOwner = new WeakReference<>(provider);
mState = INITIALIZED;
}
/**
* 计算目标State
* 由于要保持“不变性”,被计算的observer的State必要小于等于mState及在它之前添加的观察者的State
*/
private State calculateTargetState(LifecycleObserver observer) {
Entry<LifecycleObserver, ObserverWithState> previous = mObserverMap.ceil(observer);
State siblingState = previous != null ? previous.getValue().mState : null;
State parentState = !mParentStates.isEmpty() ? mParentStates.get(mParentStates.size() - 1)
: null;
return min(min(mState, siblingState), parentState);
}
/**
* 添加观察者,核心是把观察者的状态驱动到目标状态
*/
@Override
public void addObserver(@NonNull LifecycleObserver observer) {
State initialState = mState == DESTROYED ? DESTROYED : INITIALIZED;
//我们定义的LifecycleObserver只关心事件发生后的行为,并没有保存状态
//因此做一层包装,做个有状态的观察者,ObserverWithState的定义在下方
ObserverWithState statefulObserver = new ObserverWithState(observer, initialState);
//putIfAbsent,如果之前没有添加过就添加,添加过则返回之前的对象
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++;
//新添加的observer的state被驱动到目标state
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--;
}
/**
* 移除观察者,详细阐述了为什么移除观察者的时候没有发送“反向”的事件
*/
@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);
}
/**
* 做个有状态的观察者
*/
static class ObserverWithState {
State mState;
LifecycleEventObserver mLifecycleObserver;
ObserverWithState(LifecycleObserver observer, State initialState) {
//我们定义的observer又被转换了一下子
mLifecycleObserver = Lifecycling.lifecycleEventObserver(observer);
mState = initialState;
}
void dispatchEvent(LifecycleOwner owner, Event event) {
State newState = getStateAfter(event);
mState = min(mState, newState);
mLifecycleObserver.onStateChanged(owner, event);
mState = newState;
}
}
}
其实,添加和移除观察者是件简单的事情,我们通常的做法是把观察者放入一个List中,但是在这里是行不通的,因为观察者可能随时被移除,在遍历观察者通时,有的观察者可能就被移除了,这显然需要使用链表去完成。而保存观察者的容器FastSafeIterableMap就是这么一个底层以链表实现,表面上却像个Map的链表,其实现比较简单,感兴趣可以去看一下。
如果只是个简单的观察者,我们把它加到容器中也就可以了,但是这里真正的观察者是有状态的,新进的观察者在被添加到容器中时,需要被驱动到目标状态。再加上观察者可能随时被添加进来,譬如,在事件正分发的时候。所有这些情况综合在一起就使得添加观察者的代码变得比较复杂。
其中最难理解的应该是mParentStates
的作用,注释中给了一种情况,大致意思是说,在ON_START
事件分发时,某个观察者的onStart
方法中把自己给移除了,把另外一个观察者添加进去了(真尼玛是骚操作),这时候应该保证新添加的观察者的正确目标状态。嗯,虽然很难理解,但是这并不是源码的主线,我就姑且这么一说,你就姑且那么一听,就当自己懂了。
4.2 LifecycleRegistry生命周期状态的管理
把文中第一张图旋转一下,就会变成这个样子
意思是状态有上下之分,这张图有助于理解LifecycleRegistry生命周期状态间的转换。
public class LifecycleRegistry extends Lifecycle {
/**
* 直接设置当前状态,主要作用是在onSaveInstanceState时候就把状态设置为CREATED
* 为什么要这么做,Google文档中有解释
* https://developer.android.google.cn/topic/libraries/architecture/lifecycle
*/
@MainThread
public void setCurrentState(@NonNull State state) {
moveToState(state);
}
/**
* 正常情况下会调用这个方法,发送事件并更改状态
*/
public void handleLifecycleEvent(@NonNull Lifecycle.Event event) {
State next = getStateAfter(event);
moveToState(next);
}
private void moveToState(State next) {
if (mState == next) {
return;
}
mState = next;
//正在处理Event事件,或者正在添加观察者
if (mHandlingEvent || mAddingObserverCounter != 0) {
mNewEventOccurred = true;
return;
}
mHandlingEvent = true;
sync();
mHandlingEvent = false;
}
/**
* 判断所有观察者是否已经“同步”
* 同步的意思是所有的观察者都处于相同的状态
* 由之前说的“不变性”可知,最新的观察者和最老的观察者的状态如果相等,则足以说明已经同步
*/
private boolean isSynced() {
if (mObserverMap.size() == 0) {
return true;
}
State eldestObserverState = mObserverMap.eldest().getValue().mState;
State newestObserverState = mObserverMap.newest().getValue().mState;
return eldestObserverState == newestObserverState && mState == newestObserverState;
}
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 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);
}
private static Event upEvent(State state) {
switch (state) {
case INITIALIZED:
case DESTROYED:
return ON_CREATE;
case CREATED:
return ON_START;
case STARTED:
return ON_RESUME;
case RESUMED:
throw new IllegalArgumentException();
}
throw new IllegalArgumentException("Unexpected state value " + state);
}
/**
* 从前向后改变状态,由于要保持“不变性”,所以状态是向上提升的
*/
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();
}
}
}
/**
* 从后向前改变状态,由于要保持“不变性”,所以状态是向下下降的
*/
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();
}
}
}
// 把所有观察者的状态同步
private void sync() {
LifecycleOwner lifecycleOwner = mLifecycleOwner.get();
if (lifecycleOwner == null) {
throw new IllegalStateException("LifecycleOwner of this LifecycleRegistry is already"
+ "garbage collected. It is too late to change lifecycle state.");
}
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;
}
}
要完成的事情很简单,就是先改变LifecycleRegistry的状态,然后把状态“同步”到所有的观察者。听上去挺简单的,但是状态同步的途中有可能新的状态又来了,这时候所有观察者的状态只同步到了一半,你说咋办,不上不下的,所以才有了所谓的“不变性”,“不变性”方便我们去判断是否已经同步完成,但是为了在任意时刻都保持这种“不变性”,我们就需要在从前向后同步或者从后向前同步(取决于状态的上下关系)。妙啊,实在是妙啊!
5. Application的Lifecycle
什么是Application的生命周期呢?这里并不是指Application类的存活周期,而是指我们的应用在前台,或者被切换到后台这种周期,或者说是Activity们的生命周期。表达为Application的生命周期并不准确,你理解什么意思就好。我们已经知道Activity的生命周期是通过ReportFragment被报告的,Application的生命周期也得通过ReportFragment来报告,ReportFragment之前的代码被我删掉了一些东西,现在回头来看看:
public class ReportFragment extends Fragment {
private ActivityInitializationListener mProcessListener;
//以下三个方法就是为了通知Application生命周期的拥有者切换其状态
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;
}
void setProcessListener(ActivityInitializationListener processListener) {
mProcessListener = processListener;
}
interface ActivityInitializationListener {
void onCreate();
void onStart();
void onResume();
}
}
可见ReportFragment在onCreate
,onStart
,onResume
中不仅通知了Activity,还通知了Application。至于为什么onPause
,onStop
,onDestroy
没有通知Application,之后会说。
Application生命周期的拥有者:
/**
* Class that provides lifecycle for the whole application process.
* <p>
* You can consider this LifecycleOwner as the composite of all of your Activities, except that
* {@link Lifecycle.Event#ON_CREATE} will be dispatched once and {@link Lifecycle.Event#ON_DESTROY}
* will never be dispatched. Other lifecycle events will be dispatched with following rules:
* ProcessLifecycleOwner will dispatch {@link Lifecycle.Event#ON_START},
* {@link Lifecycle.Event#ON_RESUME} events, as a first activity moves through these events.
* {@link Lifecycle.Event#ON_PAUSE}, {@link Lifecycle.Event#ON_STOP}, events will be dispatched with
* a <b>delay</b> after a last activity
* passed through them. This delay is long enough to guarantee that ProcessLifecycleOwner
* won't send any events if activities are destroyed and recreated due to a
* configuration change.
*
* <p>
* It is useful for use cases where you would like to react on your app coming to the foreground or
* going to the background and you don't need a milliseconds accuracy in receiving lifecycle
* events.
*
* 注释说的很明白,总结起来就是这里的生命周期指的是Activity是否存在于前台
* 第一个Activity onStart,onResume时就会发出ON_RESUME,ON_RESUME事件
* 最后一个Activity onPause,onStop之后一小段时间后就会发出ON_PAUSE,ON_STOP事件
* 开始时会发出一次ON_CREATE事件,ON_DESTROY事件不会发出
*/
public class ProcessLifecycleOwner implements LifecycleOwner {
//避免配置发生变化(屏幕旋转等)时无谓的生命周期的变化
static final long TIMEOUT_MS = 700; //mls
// ground truth counters
private int mStartedCounter = 0;
private int mResumedCounter = 0;
private boolean mPauseSent = true;
private boolean mStopSent = true;
private Handler mHandler;
private final LifecycleRegistry mRegistry = new LifecycleRegistry(this);
private Runnable mDelayedPauseRunnable = new Runnable() {
@Override
public void run() {
dispatchPauseIfNeeded();
dispatchStopIfNeeded();
}
};
ActivityInitializationListener mInitializationListener =
new ActivityInitializationListener() {
@Override
public void onCreate() {
}
@Override
public void onStart() {
activityStarted();
}
@Override
public void onResume() {
activityResumed();
}
};
private static final ProcessLifecycleOwner sInstance = new ProcessLifecycleOwner();
/**
* The LifecycleOwner for the whole application process. Note that if your application
* has multiple processes, this provider does not know about other processes.
*
* @return {@link LifecycleOwner} for the whole application.
*/
@NonNull
public static LifecycleOwner get() {
return sInstance;
}
//初始化
static void init(Context context) {
sInstance.attach(context);
}
void activityStarted() {
mStartedCounter++;
if (mStartedCounter == 1 && mStopSent) {
mRegistry.handleLifecycleEvent(Lifecycle.Event.ON_START);
mStopSent = false;
}
}
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);
}
}
void activityStopped() {
mStartedCounter--;
dispatchStopIfNeeded();
}
void dispatchPauseIfNeeded() {
if (mResumedCounter == 0) {
mPauseSent = true;
mRegistry.handleLifecycleEvent(Lifecycle.Event.ON_PAUSE);
}
}
void dispatchStopIfNeeded() {
if (mStartedCounter == 0 && mPauseSent) {
mRegistry.handleLifecycleEvent(Lifecycle.Event.ON_STOP);
mStopSent = true;
}
}
private ProcessLifecycleOwner() {
}
void attach(Context context) {
mHandler = new Handler();
//一开始先变为CREATED状态
mRegistry.handleLifecycleEvent(Lifecycle.Event.ON_CREATE);
Application app = (Application) context.getApplicationContext();
//为所有Activity注册生命周期的回掉
app.registerActivityLifecycleCallbacks(new EmptyActivityLifecycleCallbacks() {
@Override
public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
ReportFragment.get(activity).setProcessListener(mInitializationListener);
}
//在Activity onPause方法之后被调用
@Override
public void onActivityPaused(Activity activity) {
activityPaused();
}
@Override
public void onActivityStopped(Activity activity) {
activityStopped();
}
});
}
@NonNull
@Override
public Lifecycle getLifecycle() {
return mRegistry;
}
}
这里解释一下为什么不在ReportFragmentonPause
,onStop
,onDestroy
中通知Application。答案很简单,没有必要。因为有ActivityLifecycleCallbacks回掉,我们可以在那里面完成,但是为什么又必须在ReportFragmentonCreate
,onStart
,onResume
中通知呢?因为ActivityLifecycleCallbacks相应回掉是在对应生命周期方法之后才被调用的,而这里想实现的是在这之前就发出事件。我的理解是,对于ON_RESUME
事件,通知顺序是这样的:Application->Activity;对于ON_PAUSE
事件,通知顺序是这样的:Activity->Application,其它事件类似。
ProcessLifecycleOwner是需要初始化的,并且需要尽早进行,这是在ProcessLifecycleOwnerInitializer中完成的:
public class ProcessLifecycleOwnerInitializer extends ContentProvider {
@Override
public boolean onCreate() {
LifecycleDispatcher.init(getContext());
ProcessLifecycleOwner.init(getContext());
return true;
}
}
这是个ContentProvider,它的onCreate方法是要早于Application的onCreate方法的,是个初始化的好地方,嗯,拿小本本记下来了。里面还有个LifecycleDispatcher,必然跟Lifecycle有关,去看看
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());
}
static class DispatcherActivityCallback extends EmptyActivityLifecycleCallbacks {
@Override
public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
ReportFragment.injectIfNeededIn(activity);
}
}
private LifecycleDispatcher() {
}
}
果然,是为了添加ReportFragment,前面已经说了,不保证我们的Activity都继承自兼容包,如果这样的话,ReportFragment就不会被添加到Activity中,你都不用兼容包了,看来你也是不想用Lifecycle了,这倒无所谓,但是,ReportFragment还和Application的生命周期相关,不能因为哪个Activity没用兼容包就导致Application的生命周期出现错误,所以还得保证ReportFragment被正确地添加到Activity中,LifecycleDispatcher就起到这个作用。
6. 隐藏技能
Lifecycle的源码基本上分析完了,要完成的任务其实挺简单的,但是实现起来还是挺复杂的。从源码中我们可以发现一些隐藏的“技能”:
- 应该尽量使用DefaultLifecycleObserver,而不是使用OnLifecycleEvent注解的方式,因为后者会使用反射的方式来实现观察者。
- Application在前后台切换时也会有生命周期,我们可以通过ProcessLifecycleOwner去获取。
- 监听Activity的生命周期有两种方式,第一注册ActivityLifecycleCallbacks回调,第二添加一个看不见的Fragment,并且最好是android.app.Fragment,这样适用性更广。
- ContentProvider的onCreate方法比Application的onCreate方法还要早,可以初始化一些全局性的东西,这样就不必侵入到Application中。
- 如果遍历一个集合的时候可能会增删其中的元素,应该考虑使用链表的形式存储。
Lifecycle源码中最妙的点应该是以“不变性”的方式实现观察者状态的管理。可能通用性并不是那么强,看看就好,说不定哪天吹牛逼就用上了。
7. 总结
回答文章开头提到的几个问题:
- 什么是Lifecycle?
Lifecycle是一个持有组件生命周期状态的类,它允许其它类来观察这种的状态。 - 怎样以无侵入的方式实现Lifecycle?
这里主要指怎样以无侵入的方式实现Activity的Lifecycle。关键是使用ReportFragment,这个看不见的Fragment,这样既能监听Activity的生命周期又方便通知Activity这个LifecycleOwner。 - 我们经常使用Activity和Fragment的Lifecycle,按道理说,Application也有Lifecycle,该怎么实现它的Lifecycle?
通过ProcessLifecycleOwner去实现。其实,Service也有生命周期,实现类是LifecycleService,代码很简单,这里就不展开分析了。
Lifecycle源码思想总结:
Android中拥有生命周期的类有很多,以Activity和Fragment最为常见、典型。Lifecycle的核心思想在于,尽量少的侵入到拥有生命周期的类中,而把生命周期内聚到Lifecycle
类中,Activity、Fragment等被抽象为了LifecycleOwner
。
作为核心的Lifecycle
既是Activity、Fragment等生命周期的观察者,又是LifecycleObserver
的被观察者。它既需要接收来自Activity、Fragment的生命周期事件,改变自己的状态,又需要把这种状态同步给自己所有的LifecycleObserver
。为了适应事件分发、观察者增减交织嵌套等等的复杂性,LifecycleRegistry
以一种“不变性”的方式来存储和管理所有的LifecycleObserver
,既简单又非常巧妙。
参考
Lifecycle源码分析这篇文章比较详细地解释了LifecycleRegistry状态同步的一些细节,写得很好。