一、Lifecycle
Lifecycle是Jetpack中生命周期感知型组件,用于存储如Activity 或 Fragment的生命周期状态的信息,并允许其他对象观察此状态。
Lifecycle使用状态和事件两种枚举来跟踪其关联组件的生命周期状态。
二、基本使用
使用Lifecycle观察整个Activity生命周期变化,只需通过Lifecycle类的addObserver方法将Lifecycle和观察器关联即可,每当 Activity 的生命周期方法被调用,DefaultLifecycleObserver接口的相应同名方法也会被触发。
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
// 观察者与被观察者关联
lifecycle.addObserver(MyObserver())
}
class MyObserver : DefaultLifecycleObserver {
override fun onResume(owner: LifecycleOwner) {
}
override fun onPause(owner: LifecycleOwner) {
}
}
}
因为 26.1.0 及更高版本的AppCompatActivity父类中实现了LifecycleOwner接口,所以以上代码可以直接获取lifecycle。如果有自定义类想自己实现LifecycleOwner接口,可以使用LifecycleRegistry类。
class MainActivity : Activity(), LifecycleOwner {
private lateinit var lifecycleRegistry: LifecycleRegistry
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
lifecycleRegistry = LifecycleRegistry(this)
lifecycleRegistry.currentState = Lifecycle.State.CREATED
}
public override fun onStart() {
super.onStart()
lifecycleRegistry.currentState = Lifecycle.State.STARTED
}
override fun getLifecycle(): Lifecycle {
return lifecycleRegistry
}
}
三、源码
Lifecycle类
Lifecycle是一个抽象类,实现类是LifecycleRegistry,内部包含三个抽象方法、事件和状态两个枚举类.
Even类:Lifecycle类分派的生命周期事件,这些事件映射到 Activity 和 Fragment 中的回调事件。比如Activity的onCreate方法映射为ON_CREATE
事件。
State类:由Lifecycle跟踪的组件的当前生命周期状态。
public abstract class Lifecycle {
@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)
AtomicReference<Object> mInternalScopeRef = new AtomicReference<>();
@MainThread
public abstract void addObserver(@NonNull LifecycleObserver observer);
@MainThread
public abstract void removeObserver(@NonNull LifecycleObserver observer);
@MainThread
public abstract State getCurrentState();
public enum Event {
ON_CREATE,
ON_START,
ON_RESUME,
ON_PAUSE,
ON_STOP,
ON_DESTROY,
ON_ANY
}
@SuppressWarnings("WeakerAccess")
public enum State {
DESTROYED,
INITIALIZED,
CREATED,
STARTED,
RESUMED;
public boolean isAtLeast(@NonNull State state) {
return compareTo(state) >= 0;
}
}
}
ReportFragment类
ReportFragment是一个无UI的Fragment,在AppCompatActivity继承的ComponentActivity的onCreate方法中被添加,ReportFragment的生命周期和绑定的Activity的生命周期完全对应,以下代码中每个生命周期方法都会执行dispatch方法,将对应事件传递出去,也就是处理Activiti的生命周期事件。
ReportFragment的dispatch方法会判断Activity是否实现了LifecycleOwner接口或LifecycleRegistryOwner(已被废弃),最后会调用LifecycleRegister的handleLifecycleEvent方法,并将Event传递到LifecycleRegistry类。
static void dispatch(@NonNull Activity activity, @NonNull Lifecycle.Event event) {
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);
}
}
}
@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;
}
LifecycleRegistry类
LifecycleRegistry类是Lifecycle的实现类,实现了具体的事件回调和状态管理,addObserver方法接收到观察者(LifecycleObserver)后,通过ObserverWithState传给Lifecycling包装为LifecycleEventObserver对像,最后统一通过LifecycleEventObserver.onStateChanged分发,其中通过反射获取到LifecycleObserver的所有信息。
@Override
public void addObserver(@NonNull LifecycleObserver observer) {
State initialState = mState == DESTROYED ? DESTROYED : INITIALIZED;
ObserverWithState statefulObserver = new ObserverWithState(observer, initialState);
...
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);
}
...
}
static class ObserverWithState {
State mState;
LifecycleEventObserver mLifecycleObserver;
ObserverWithState(LifecycleObserver observer, State initialState) {
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;
}
}
另一方面,LifecycleRegistry收到ReportFragment的Event后,会根据Event转换为对应的State,然后更新本地的 mState
,如果状态不同会执行sync方法同步宿主和Lifecycle的生命周期。
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;
}
事件与状态转换以及生命周期同步如下图,借助官方提供的图更易理解。
从左往右的箭头为前进事件,从右往左为倒退事件,在sync方法中会比较枚举值的大小来决定执行前进或倒退,即forwardPass方法和backwardPass方法。
假设当前Lifecycle的mState为
STATRTED状态,当ReportFragment传递过来的事件为ON_RESUME,这时事件前进mState
就转变为RESUMED;当ReportFragment传递过来的事件为ON_STOP,这时事件倒退mState
就转变为CREATED。
本地mState状态更新后,会调用ObserverWithState.dispatchEvent方法进行事件通知。
private void sync() {
LifecycleOwner lifecycleOwner = mLifecycleOwner.get();
...
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);
}
}
}
四、总结
1、26.1.0 及更高版本的AppCompatActivity和Fragment都实现了LifecycleOwner 接口,所以可以直接获取getLifecycle
;
2、ComponentActivity
类onCreate方法中绑定了一个无 UI 的ReportFragment,ReportFragment生命周期与Activity完全一致,内部对29以上或以下的系统获取生命周期事件方式做了区分;
3、
LifecycleRegistry 会将外部addObserver
传进来的LifecycleObserver对象包装成 LifecycleEventObserver对象,通过调用 LifecycleEventObserver的onStateChanged
方法来完成事件回调。