在 androidx.lifecycle 相关包名目录下,有很多 Lifecycle 相关的源码,如上图所示。其中起到核心作用的一个类是:LifecycleRegistry
。
LifecycleRegistry:
可以处理多个观察者的 Lifecycle 实现。
它被 Frangments 和 Activities 所使用。 如果您有自定义 LifecycleOwner
,也可以直接使用它。
Lifecycle 声明了添加观察者,移除观察者,获取当前生命周期状态三个抽象方法
而 LifecycleRegistry 则是其子类,他是观察者和被观察者的纽带,能够管理多个观察者;被观察者的生命周期事件都是通过该类 handleLifecycleEvent
方法进行下发的。
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),
*/
private FastSafeIterableMap<LifecycleObserver, ObserverWithState> mObserverMap =
new FastSafeIterableMap<>();
/**
* Current state
*/
private State mState;
/**
* 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; //使用弱引用避免Activity/Fragment内存泄漏
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.
private ArrayList<State> mParentStates = new ArrayList<>();
/**
* 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;
}
/**
* Moves the Lifecycle to the given state and dispatches necessary events to the observers.
*
* @param state new state
* @deprecated Use {@link #setCurrentState(State)}.
*/
@Deprecated
@MainThread
public void markState(@NonNull State state) {
setCurrentState(state);
}
/**
* Moves the Lifecycle to the given state and dispatches necessary events to the observers.
*
* @param state new state
*/
@MainThread
public void setCurrentState(@NonNull State state) {
moveToState(state);
}
//设置当前状态并通知观察者。请注意,如果 currentState 与上次调用此方法的状态相同,则调用此方法无效。
public void handleLifecycleEvent(@NonNull Lifecycle.Event event) {
State next = getStateAfter(event);
moveToState(next);
}
private void moveToState(State next) {
//1. 如果状态和当前状态一样,则不需要下发事件通知
if (mState == next) {
return;
}
//2. 更新最新生命周期事件状态
mState = next;
if (mHandlingEvent || mAddingObserverCounter != 0) {
mNewEventOccurred = true;
// we will figure out what to do on upper level.
return;
}
//3. 表示当前正在处理事件
mHandlingEvent = true;
//4. 同步事件到各Observer
sync();
//5. 同步结束,重置标志
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;
}
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;
//创建一个带状态的Observer,可以理解为是observer的包装器
ObserverWithState statefulObserver = new ObserverWithState(observer, initialState);
//将observer以及带状态的observer保存到map中
ObserverWithState previous = mObserverMap.putIfAbsent(observer, statefulObserver);
//如果observer存在则无需添加,直接返回
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--;
}
private void popParentState() {
mParentStates.remove(mParentStates.size() - 1);
}
private void pushParentState(State state) {
mParentStates.add(state);
}
@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);
}
/**
* The number of observers.
*
* @return The number of observers.
*/
@SuppressWarnings("WeakerAccess")
public int getObserverCount() {
return mObserverMap.size();
}
@NonNull
@Override
public State getCurrentState() {
return mState;
}
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
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();
}
}
}
// happens only on the top of stack (never in reentrance),
// so it doesn't have to take in account parents
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;
}
static State min(@NonNull State state1, @Nullable State state2) {
return state2 != null && state2.compareTo(state1) < 0 ? state2 : state1;
}
//带状态的Observer
static class ObserverWithState {
State mState;
LifecycleEventObserver mLifecycleObserver;
ObserverWithState(LifecycleObserver observer, State initialState) {
//TODO 此处,感兴趣可以进去仔细研究
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;
}
}
}
通过上面代码我们知道 handleLifecycleEvent
事件最后传递给 observer 的 dispatchEvent 方法中了。那么这个 observer 是什么?首先看下它的类是 ObserverWithState
,它是在什么时候被创建的呢?答案是 addObserver
方法。
可以看到在 ObserverWithState
的 dispatchEvent
方法最终将事件委托给 mLifecycleObserver
,可以看到这个 LifecycleEventObserver
类其实是 ReflectiveGenericLifecycleObserver
类型。ReflectiveGenericLifecycleObserver
使用了反射机制类调用方法,为了减少反射带来的性能问题,它做了哪些优化?可以看下 ClassesInfoCache
和 Lifecycling
里的相关源码。
生命周期感知型组件可执行操作来响应另一个组件(如 Activity 和 Fragment)的生命周期状态的变化。这些组件有助于您编写出更有条理且往往更精简的代码,此类代码更易于维护。
一种常见的模式是在 Activity 和 Fragment 的生命周期方法中实现依赖组件的操作。但是,这种模式会导致代码条理性很差而且会扩散错误。通过使用生命周期感知型组件,你可以将依赖组件的代码从生命周期方法移入组件本身中。
androidx.lifecycle
软件包提供了可用于构建生命周期感知型组件的类和接口 - 这些组件可以根据 Activity 或 Fragment 的当前生命周期状态自动调整其行为。
在 Android 框架中定义的大多数应用组件都存在生命周期。生命周期由操作系统或进程中运行的框架代码管理。它们是 Android 工作原理的核心,应用必须遵循它们。如果不这样做,可能会引发内存泄漏甚至应用崩溃。
Lifecycle
是一个类,用于存储有关组件(如 Activity 或 Fragment)的生命周期状态的信息,并允许其他对象观察此状态。
States:
从框架和 Lifecycle
类分派的生命周期事件。这些事件映射到 Activity 和 Fragment 中的回调事件。
Events:
由 Lifecycle
对象跟踪的组件的当前状态。
类可以通过实现
DefaultLifecycleObserver
并替换相应的方法(如 onCreate
和 onStart
等)来监控组件的生命周期状态。然后,您可以通过调用 Lifecycle
类的 addObserver()
方法并传递观察器的实例来添加观察器。
Lifecycle:
定义一个具有 Android 生命周期的对象。 Fragment 和 FragmentActivity 类实现 LifecycleOwner
接口,该接口具有访问 Lifecycle 的 getLifecycle 方法。你还可以在自己的类中实现 LifecycleOwner
。
该类中的 Lifecycle.Event.ON_CREATE、Lifecycle.Event.ON_START、Lifecycle.Event.ON_RESUME 事件在 LifecycleOwner 的相关方法返回后调用。此类中的 Lifecycle.Event.ON_PAUSE、Lifecycle.Event.ON_STOP、Lifecycle.Event.ON_DESTROY 事件是在调用 LifecycleOwner 的相关方法之前调度的。例如,Lifecycle.Event.ON_START 将在 onStart 返回后调度,Lifecycle.Event.ON_STOP 将在 onStop 被调用之前调度。这为您提供了有关所有者所处状态的某些保证。
如果您使用 Java 8 语言,则使用 DefaultLifecycleObserver
观察事件。要包含它,你应该将“androidx.lifecycle:common-java8:<version>”添加到您的 build.gradle 文件中。
比如 TestObserver 类,实现 DefaultLifecycleObserver {
@覆盖
public void onCreate(LifecycleOwner owner) {
// 你的代码
}
}
如果您使用 Java 7 语言,则使用注释观察生命周期事件。一旦 Java 8 Language 在 Android 上成为主流,注解将被弃用,因此在 DefaultLifecycleObserver 和注解之间,您必须始终选择 DefaultLifecycleObserver
。
TestObserver 类,实现 LifecycleObserver {
@OnLifecycleEvent(ON_STOP)
void onStopped() {}
}
观察者方法可以接收零个或一个参数。如果使用,第一个参数必须是 LifecycleOwner 类型。用 Lifecycle.Event.ON_ANY 注释的方法可以接收第二个参数,它必须是 Lifecycle.Event 类型。
TestObserver 类, 实现 LifecycleObserver {
@OnLifecycleEvent(ON_CREATE)
void onCreated(LifecycleOwner source) {}
@OnLifecycleEvent(ON_ANY)
void onAny(LifecycleOwner source, Event event) {}
}
提供这些附加参数是为了让您可以方便地观察多个提供者和事件,而无需手动跟踪它们。
public abstract class Lifecycle {
/**
* Lifecycle coroutines extensions stashes the CoroutineScope into this field.
*
* @hide used by lifecycle-common-ktx
*/
@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)
@NonNull
AtomicReference<Object> mInternalScopeRef = new AtomicReference<>();
/**
* Adds a LifecycleObserver that will be notified when the LifecycleOwner changes
* state.
* <p>
* The given observer will be brought to the current state of the LifecycleOwner.
* For example, if the LifecycleOwner is in {@link State#STARTED} state, the given observer
* will receive {@link Event#ON_CREATE}, {@link Event#ON_START} events.
*
* @param observer The observer to notify.
*/
@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>
*
* @param observer The observer to be removed.
*/
@MainThread
public abstract void removeObserver(@NonNull LifecycleObserver observer);
/**
* Returns the current state of the Lifecycle.
*
* @return The current state of the Lifecycle.
*/
@MainThread
@NonNull
public abstract State getCurrentState();
@SuppressWarnings("WeakerAccess")
public enum Event {
/**
* Constant for onCreate event of the {@link LifecycleOwner}.
*/
ON_CREATE,
/**
* Constant for onStart event of the {@link LifecycleOwner}.
*/
ON_START,
/**
* Constant for onResume event of the {@link LifecycleOwner}.
*/
ON_RESUME,
/**
* Constant for onPause event of the {@link LifecycleOwner}.
*/
ON_PAUSE,
/**
* Constant for onStop event of the {@link LifecycleOwner}.
*/
ON_STOP,
/**
* Constant for onDestroy event of the {@link LifecycleOwner}.
*/
ON_DESTROY,
/**
* An {@link Event Event} constant that can be used to match all events.
*/
ON_ANY
}
/**
* Lifecycle states. You can consider the states as the nodes in a graph and
* {@link Event}s as the edges between these nodes.
*/
@SuppressWarnings("WeakerAccess")
public enum State {
/**
* Destroyed state for a LifecycleOwner. After this event, this Lifecycle will not dispatch
* any more events. For instance, for an {@link android.app.Activity}, this state is reached
* <b>right before</b> Activity's {@link android.app.Activity#onDestroy() onDestroy} call.
*/
DESTROYED,
/**
* Initialized state for a LifecycleOwner. For an {@link android.app.Activity}, this is
* the state when it is constructed but has not received
* {@link android.app.Activity#onCreate(android.os.Bundle) onCreate} yet.
*/
INITIALIZED,
/**
* Created state for a LifecycleOwner. For an {@link android.app.Activity}, this state
* is reached in two cases:
* <ul>
* <li>after {@link android.app.Activity#onCreate(android.os.Bundle) onCreate} call;
* <li><b>right before</b> {@link android.app.Activity#onStop() onStop} call.
* </ul>
*/
CREATED,
/**
* Started state for a LifecycleOwner. For an {@link android.app.Activity}, this state
* is reached in two cases:
* <ul>
* <li>after {@link android.app.Activity#onStart() onStart} call;
* <li><b>right before</b> {@link android.app.Activity#onPause() onPause} call.
* </ul>
*/
STARTED,
/**
* Resumed state for a LifecycleOwner. For an {@link android.app.Activity}, this state
* is reached after {@link android.app.Activity#onResume() onResume} is called.
*/
RESUMED;
/**
* Compares if this State is greater or equal to the given {@code state}.
*
* @param state State to compare with
* @return true if this State is greater or equal to the given {@code state}
*/
public boolean isAtLeast(@NonNull State state) {
return compareTo(state) >= 0;
}
}
}
Activity 的生命周期事件是如何被转发到 LifecycleRegistry
中的,LifecycleRegistry
类 和 java 中 Observable 类有点像;因为 Lifecycle 的设计思想有部分就是使用了观察者模式,LifecycleRegistry 类中可以注册或反注册多个观察者,一旦生命周期发生变更 LifecycleRegistry
会及时通知所有的观察者,这样就达到了观察者能够感知带生命周期组件的变化了。
LifecycleOwner:
LifecycleOwner
是单一方法接口,表示类具有 Lifecycle。它具有一种方法(即 getLifecycle()),该方法必须由类实现。如果您尝试管理整个应用进程的生命周期,请参阅 ProcessLifecycleOwner
。
此接口从各个类(如 Fragment 和 AppCompatActivity)抽象化 Lifecycle 的所有权,并允许编写与这些类搭配使用的组件。任何自定义应用类均可实现 LifecycleOwner 接口。
实现 DefaultLifecycleObserver 的组件可与实现 LifecycleOwner 的组件完美配合,因为所有者可以提供生命周期,而观察者可以注册以观察生命周期。
一个常见的用例是,如果 Lifecycle
现在未处于良好的状态,则应避免调用某些回调。例如,如果回调在 Activity 状态保存后运行 Fragment 事务,就会触发崩溃,因此我们绝不能调用该回调。
为简化此使用场景,Lifecycle
类允许其他对象查询当前状态。
如果库提供了需要使用 Android 生命周期的类,我们建议您使用生命周期感知型组件。你可以轻松集成这些组件,而无需在客户端进行手动生命周期管理。
实现自定义 LifecycleOwner
如果您有一个自定义类并希望使其成为 LifecycleOwner
,您可以使用 LifecycleRegistry 类,但需要将事件转发到该类,如以下代码示例中所示:
class MyActivity : Activity(), LifecycleOwner {
private lateinit var lifecycleRegistry: LifecycleRegistry
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
lifecycleRegistry = LifecycleRegistry(this)
lifecycleRegistry.markState(Lifecycle.State.CREATED)
}
public override fun onStart() {
super.onStart()
lifecycleRegistry.markState(Lifecycle.State.STARTED)
}
override fun getLifecycle(): Lifecycle {
return lifecycleRegistry
}
}
生命周期感知型组件的最佳做法
- 使界面控制器(Activity 和 Fragment)尽可能保持精简。它们不应试图获取自己的数据,而应使用
ViewModel
执行此操作,并观察LiveData
对象以将更改体现到视图中。 - 设法编写数据驱动型界面,对于此类界面,界面控制器的责任是随着数据更改而更新视图,或者将用户操作通知给
ViewModel
。 - 将数据逻辑放在
ViewModel
类中。ViewModel
应充当界面控制器与应用其余部分之间的连接器。不过要注意,ViewModel
不负责获取数据(例如,从网络获取)。但是,ViewModel
应调用相应的组件来获取数据,然后将结果提供给界面控制器。 - 使用数据绑定在视图与界面控制器之间维持干净的接口。这样一来,您可以使视图更具声明性,并尽量减少需要在 Activity 和 Fragment 中编写的更新代码。如果您更愿意使用 Java 编程语言执行此操作,请使用诸如 Butter Knife 之类的库,以避免样板代码并实现更好的抽象化。
- 如果界面很复杂,不妨考虑创建 presenter 类来处理界面的修改。这可能是一项艰巨的任务,但这样做可使界面组件更易于测试。
- 避免在 ViewModel 中引用 View 或 Activity 上下文。如果
ViewModel
存在的时间比 Activity 更长(在配置更改的情况下),Activity 将泄漏并且不会获得垃圾回收器的妥善处置。 - 使用 Kotlin 协程 管理长时间运行的任务和其他可以异步运行的操作。
生命周期感知型组件的用例
生命周期感知型组件可使您在各种情况下更轻松地管理生命周期。下面列举几个例子:
- 在粗粒度和细粒度位置更新之间切换。使用生命周期感知型组件可在位置应用可见时启用细粒度位置更新,并在应用位于后台时切换到粗粒度更新。借助生命周期感知型组件
LiveData
,应用可以在用户使用位置发生变化时自动更新界面。 - 停止和开始视频缓冲。使用生命周期感知型组件可尽快开始视频缓冲,但会推迟播放,直到应用完全启动。此外,应用销毁后,您还可以使用生命周期感知型组件终止缓冲。
- 开始和停止网络连接。借助生命周期感知型组件,可在应用位于前台时启用网络数据的实时更新(流式传输),并在应用进入后台时自动暂停。
- 暂停和恢复动画可绘制资源。借助生命周期感知型组件,可在应用位于后台时暂停动画可绘制资源,并在应用位于前台后恢复可绘制资源。