LifeCycle用于帮助开发者管理Activity和Fragment 的生命周期。
介绍Lifecycle之前,首先需要了解观察者模式。
观察者模式首先需要被观察者和被观察者,被观察者里面可以添加观察者和删除观察者,以及有事件的时候通知观察的方法。而观察者则事收到事件的回调之后,即做出相应的处理。
而Lifecycle则是典型的观察者模式。
LifecycleOwner可以理解为被观察者。而它所有的处理全部在LifecycleRegistry中。
那那些又可以当作被观察者了?其实只要我们在一个类中取实现LifecycleOwner,然后在对应的生命周期去设置不同的Lifecycle.State,这样即可。
public class MyActivity extends Activity implements LifecycleOwner {
private LifecycleRegistry mLifecycleRegistry;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mLifecycleRegistry = new LifecycleRegistry(this);
mLifecycleRegistry.setCurrentState(Lifecycle.State.CREATED);
}
@Override
protected void onDestroy() {
super.onDestroy();
mLifecycleRegistry.setCurrentState(Lifecycle.State.DESTROYED);
}
@NonNull
@Override
public Lifecycle getLifecycle() {
return mLifecycleRegistry;
}
}
那同样的道理就是我们只要实现了LifecycleObserver就可以作为观察者。
public class LifecycleObserverImpl implements LifecycleObserver {
@OnLifecycleEvent(Lifecycle.Event.ON_CREATE)
public void onCreate(){
Log.e("zzf","---------onCreate--------");
}
@OnLifecycleEvent(Lifecycle.Event.ON_START)
public void onStart(){
Log.e("zzf","---------onStart--------");
}
@OnLifecycleEvent(Lifecycle.Event.ON_RESUME)
public void onResume(){
Log.e("zzf","---------onResume--------");
}
@OnLifecycleEvent(Lifecycle.Event.ON_PAUSE)
public void onPause(){
Log.e("zzf","---------onPause--------");
}
@OnLifecycleEvent(Lifecycle.Event.ON_STOP)
public void onStop(){
Log.e("zzf","---------onStop--------");
}
@OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
public void onDestory(){
Log.e("zzf","---------onDestory--------");
}
}
那么有个问题来了,我们在观察者上面对应的Lifecycle.Event,而在被观察者的是设置Lifecycle.State,那这个Event和State是怎样关联起来的?
那下面以ComponentActivity为例来讲讲整个流程。
public class ComponentActivity extends androidx.core.app.ComponentActivity implements
LifecycleOwner {
}
```LifecycleOwner
我们可以看到,ComponentActivity是实现了LifecycleOwner接口。
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mSavedStateRegistryController.performRestore(savedInstanceState);
ReportFragment.injectIfNeededIn(this);
if (mContentLayoutId != 0) {
setContentView(mContentLayoutId);
}
}
然后在oncreate中添加一个没有页面的ReportFragment,我们知道Fragment的生命周期和activity的生命周期是一致的,这让我们想到Glide的生命周期管理好像也是采用这种方法。
所以接下来我们看在ReportFragment的生命周期中做了啥。
@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;
}
在生命周期中调用dispatch方法.
private void dispatch(Lifecycle.Event event) {
Activity activity = getActivity();
if (activity instanceof LifecycleOwner) {
Lifecycle lifecycle = ((LifecycleOwner) activity).getLifecycle();
if (lifecycle instanceof LifecycleRegistry) {
((LifecycleRegistry) lifecycle).handleLifecycleEvent(event);
}
}
}
继续调用LifecycleRegistry的handleLifecycleEvent()。
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()。
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;
}
mState.compareTo(mObserverMap.eldest().getValue().mState) < 0 从缓存的观察者中拿出最旧的状态,与当前状态进行比较,如果小于 0, 说明观察者的状态提前于当前状态,那么就执行一个backwardPass(lifecycleOwner) 方法,让观察者的状态回退到当前状态上
mState.compareTo(newest.getValue().mState) > 0 这个判断正好和上面相反,说明当前的观察者状态落后于当前状态,那么就让观察者的状态追上当前状态,执行 forwardPass(lifecycleOwner)
通过分析 forwardPass 和 backwardPass 方法,我们看到其内部又调用了两个方法, downEvent 和 upEvent,我们称呼为升级事件和降级事件
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);
}
在这个就回答了前面的哪个疑问,Event和state是怎样转换的。
在backwardPass或forwardPass方法中最终调用的是dispatchEvent方法,进而调用mLifecycleObserver.onStateChanged(owner, event)。
前面我们说了一大堆,都是对 Lifecycle 如何处理,并监听我们的生命周期的方法,也就是 Lifecycle是如何处理监听的。那么我们前面一直都没有说过,观察者那里来的?????????
好,我们继续观察 LifecycleRegister 中的 addObserver(LifecycleObserver) 这个也是我们自定义观察者后,需要调用的方法
@Override
public void addObserver(@NonNull LifecycleObserver observer) {
State initialState = mState == DESTROYED ? DESTROYED : INITIALIZED;
ObserverWithState statefulObserver = new ObserverWithState(observer, initialState);
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++;
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--;
}
创建了一个 ObserverWithState ,这是一个有状态的观察者,从名字上我们就可以看出来。两个参数分别是我们传入的观察者和我们刚刚创建好的状态。这是个装饰器模式,目的是给原对象,增加一个新属性,但又不改变原数据结构的方案。
紧接着又把这个观察者和带有状态的观察者,放进了事先已经创建好的 Map 中,也就是 mObserverMap 然后返回了个东西, 阅读后发现,又和 Lifecycle 的注释对上了。
之后,计算出当前 Activity 或 Fragment 的状态,并判断,如果当前观察者的状态落后于 Activity 或 Fragment 的状态,则立即执行dispatchEvent() 方法,执行回调。