原理
- 观察者设计模式
- activity是被观察者。其他想知道activity生命周期状态的类是观察者
使用
- 被观察者继承LifecycleOwner(AppCompatActivity已继承),观察者继承LifecycleObserver
- 在被观察者中添加观察者到观察者列表。完成订阅关系
activity.getLifecycle().addObserver(presenter);
- 观察者定义自己的函数来订阅对应的生命周期
@OnLifecycleEvent(Lifecycle.Event.ON_CREATE)
void onCreateX(LifecycleOwner owner) {}
源码
- 看一下LifecycleRegister 类中的addObserver方法
这里你会发现生成了一个ObserverWithState,然后放入FastSafeIterableMap里,这个类
是一个自定义列表,用于保存观察者并可在遍历期间处理删除/添加。
@Overridepublic 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 quicklyreturn;}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 recalculatetargetState = calculateTargetState(observer);}if (!isReentrance) {// we do sync only on the top level.sync();}mAddingObserverCounter--;}
-
从第一行代码可看出初始State应该是 INITIALIZED
-
查看State知道有五个状态,从小到大分别对应
public enum State {DESTROYED,INITIALIZED,CREATED,STARTED,RESUMED;public boolean isAtLeast(@NonNull State state) {return compareTo(state) >= 0;}}
-
AppCompatActivity 实现了LifecycleOwner接口,同时持有实现了Lifecycle的LifecycleRegistry对象,这个对象就可以将其理解为观察者模式中的Observable,LifecycleRegistr聚合多个LifecycleObserver,生命周期改变时通知LifecycleObserver进行相应的方法调用。
-
AppCompatActivity 继承的 androidx.core.app.ComponentActivity中的onCretae方法
ReportFragment.injectIfNeededIn(this);
就是在当前的Activity里添加一个ReportFragment。 -
查看ReportFragment源码,代码量很少
@SuppressWarnings("UnknownNullness") // TODO https://issuetracker.google.com/issues/112197238
@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP_PREFIX)
public class ReportFragment extends Fragment {private static final String REPORT_FRAGMENT_TAG = "androidx.lifecycle"+ ".LifecycleDispatcher.report_fragment_tag";public static void injectIfNeededIn(Activity activity) {// ProcessLifecycleOwner should always correctly work and some activities may not extend// FragmentActivity from support lib, so we use framework fragments for activitiesandroid.app.FragmentManager manager = activity.getFragmentManager();if (manager.findFragmentByTag(REPORT_FRAGMENT_TAG) == null) {manager.beginTransaction().add(new ReportFragment(), REPORT_FRAGMENT_TAG).commit();// Hopefully, we are the first to make a transaction.manager.executePendingTransactions();}}static ReportFragment get(Activity activity) {return (ReportFragment) activity.getFragmentManager().findFragmentByTag(REPORT_FRAGMENT_TAG);}private ActivityInitializationListener mProcessListener;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();}}@Overridepublic void onActivityCreated(Bundle savedInstanceState) {super.onActivityCreated(savedInstanceState);dispatchCreate(mProcessListener);dispatch(Lifecycle.Event.ON_CREATE);}@Overridepublic void onStart() {super.onStart();dispatchStart(mProcessListener);dispatch(Lifecycle.Event.ON_START);}@Overridepublic void onResume() {super.onResume();dispatchResume(mProcessListener);dispatch(Lifecycle.Event.ON_RESUME);}@Overridepublic void onPause() {super.onPause();dispatch(Lifecycle.Event.ON_PAUSE);}@Overridepublic void onStop() {super.onStop();dispatch(Lifecycle.Event.ON_STOP);}@Overridepublic void onDestroy() {super.onDestroy();dispatch(Lifecycle.Event.ON_DESTROY);// just want to be sure that we won't leak reference to an activitymProcessListener = null;}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);}}}void setProcessListener(ActivityInitializationListener processListener) {mProcessListener = processListener;}interface ActivityInitializationListener {void onCreate();void onStart();void onResume();}
}
-
查看injectIfNeededIn函数可知就是在activity里面创建了一个没有UI的fragment。
-
看ReportFragment的生命周期函数
你会发现都调用了dispatch()方法 -
而dispatch()方法则会判断Activity是否实现了LifecycleOwner接口,如果实现了该接口就调用LifecycleRegister的handleLifecycleEvent()
这样生命周期的状态就会借由LifecycleRegistry通知给各个LifecycleObserver从而调用其中对应Lifecycle.Event的方法。这种通过Fragment来感知Activity生命周期的方法其实在Glide的中也是有体现的。 -
回到handleLifecycleEvent方法中
State next = getStateAfter(event);
事件发生的时候,先得到当前activity应该出现的下一个状态
public void handleLifecycleEvent(@NonNull Lifecycle.Event event) {State next = getStateAfter(event);moveToState(next);
}
- 更新现在的状态
moveToState(next);
mState = next;更新现在的状态
sync();backwardPass(lifecycleOwner);//逆推forwardPass(lifecycleOwner);//正推//从图表上分析
- 找到观察者
- 在addObserver的new ObserverWithState里有生成对应的ObserverWithState。
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();}}}
- 接下来就是调用onStateChanged(),来通知 实现了 LifecycleObserver的类,生命周期发生了变化
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;}}
-
在ObserverWithState的构造函数中有调用lifecycleEventObserver,里面就是用反射拿到观察者的信息并保存在ReflectiveGenericLifecycleObserver里面
-
查看实现类
ReflectiveGenericLifecycleObserver的onStateChanged()
ReflectiveGenericLifecycleObserver。的构造方法中就把presenter中的方法和注解保存了下来
再通过onStateChanged()进行生命周期的方法的调用
class ReflectiveGenericLifecycleObserver implements LifecycleEventObserver {private final Object mWrapped;private final CallbackInfo mInfo;ReflectiveGenericLifecycleObserver(Object wrapped) {mWrapped = wrapped;mInfo = ClassesInfoCache.sInstance.getInfo(mWrapped.getClass());}@Overridepublic void onStateChanged(LifecycleOwner source, Event event) {mInfo.invokeCallbacks(source, event, mWrapped);}
}