关键字:Lifecycle
源码分析基于 androidx.appcompat:appcompat:1.2.0
1.什么是Lifecycle?
Lifecycle翻译过来就是生命周期,它可以使组件A可以监听具有生命周期的组件B,例如Presenter监听Activity生命周期。
2.为什么会有Lifecycle?
(1)可以将跟生命周期相关的逻辑抽离出来,例如某工具,需要在onStart启动、onStop关闭,那么工具就可以监听生命周期变化,将逻辑从view中抽离出来;
(2)可以解决内存泄漏问题,Presenter需要View在onDestory中关闭回调,现在Presenter自身监听生命周期变化完成关闭回调操作;
3.Lifecycle如何实现的?
剧透下,跟Glide类似,给Activity添加空白Fragment,然后实现生命周期分发;自定义Activity继承FragmentActivity,后者继承ComponentActivity,所以关键看ComponentActivity;
Step 1:ComponentActivity构造函数
public class ComponentActivity extends androidx.core.app.ComponentActivity implements
LifecycleOwner,
ViewModelStoreOwner,
SavedStateRegistryOwner,
OnBackPressedDispatcherOwner {
......
private final LifecycleRegistry mLifecycleRegistry = new LifecycleRegistry(this);
......
public ComponentActivity() {
Lifecycle lifecycle = getLifecycle();
......
getLifecycle().addObserver(new LifecycleEventObserver() {
@Override
public void onStateChanged(@NonNull LifecycleOwner source,
@NonNull Lifecycle.Event event) {
if (event == Lifecycle.Event.ON_DESTROY) {
if (!isChangingConfigurations()) {
getViewModelStore().clear();
}
}
}
});
......
}
(1)成员变量mLifecycleRegistry ,从字面上判断是跟注册有关的,它包括监听器集合、被监听者当前状态、被监听者的弱引用;如果项目support包没法升级,可以通过创建LifecycleRegistry来实现生命周期分发;
(2)再看构造函数,默认注册LifecycleEventObserver监听,当发生ON_DESTROY事件时且不是因为屏幕旋转导致,将回调getViewModelStore().clear(),提供一个清理ViewModel数据的机会;
Step 2:ComponentActivity.onCreate
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mSavedStateRegistryController.performRestore(savedInstanceState);
ReportFragment.injectIfNeededIn(this);
......
}
主要是添加ReportFragment,ReportFragment.injectIfNeededIn跟进去看看;
Step 2:ReportFragment.injectIfNeededIn
public static void injectIfNeededIn(Activity activity) {
android.app.FragmentManager manager = activity.getFragmentManager();
if (manager.findFragmentByTag(REPORT_FRAGMENT_TAG) == null) {
manager.beginTransaction().add(new ReportFragment(), REPORT_FRAGMENT_TAG).commit();
manager.executePendingTransactions();
}
}
代码很简单,就是给当前Activity添加ReportFragment,到这里大概能猜到,就是通过ReportFragment来监听事件以及分发事件;
Step 3:事件分发ReportFragment.onActivityCreated
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
......
dispatch(Lifecycle.Event.ON_CREATE);
}
以onCreate为例,onActivityCreated被触发,将分发ON_CREATE事件,dispatch(Lifecycle.Event.ON_CREATE)跟进去看看;
Step 4:事件分发ReportFragment.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);
}
}
}
调用我们前面提到的ComponentActivity 成员变量mLifecycleRegistry.handleLifecycleEvent 分发事件,跟进去看看;
Step 5:事件分发LifecycleRegistry.handleLifecycleEvent->LifecycleRegistry.moveToState
private void moveToState(State next) {
......
mHandlingEvent = true;
sync();
mHandlingEvent = false;
}
LifecycleRegistry.handleLifecycleEvent主要是调用了moveToState实现分发,关键是sync这个方法,跟进去看看;
Step 6:事件分发LifecycleRegistry.sync
private void sync() {
while (!isSynced()) {
mNewEventOccurred = false;
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;
}
(1)这里做事件分发的处理,大家一定很奇怪为什么会有backwardPass以及forwardPass,等会解释;
(2)有两个概念:Event以及State,都是枚举被定义在Lifecycle当中;
Event对应生命周期方法,这个很好理解;
public enum Event {
//值从上到下增大;
ON_CREATE,
ON_START,
ON_RESUME,
ON_PAUSE,
ON_STOP,
ON_DESTROY,
ON_ANY
}
State对应状态值,
起始状态为INITIALIZED,
当Event 执行到onCreate,State为CREATED;
当Event 执行到onStart,State为STARTED;
当Event 执行到onResume,State为RESUMED;
目前为止,State 是由小到大,下面就很关键:
当Event 执行到onPause,State为STARTED;
当Event 执行到onStop,State为CREATED;
当Event 执行到onDestory,State为DESTROYED;
######这里State 是由大到小,为什么这样设计,我也没搞懂,只能先这么理解。
public enum State {
//值从上到下增大;
DESTROYED,
INITIALIZED,
CREATED,
STARTED,
RESUMED;
}
(3)上面提到,State 会经历由小到大,由大到小的过程,那么由小到大,就是执行forwardPass,那么由大到小,就是执行backwardPass;
LifecycleRegistry.backwardPass
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);
......
observer.dispatchEvent(lifecycleOwner, event);
......
}
}
}
(1)downEvent,获取当前state的下一个event ,例如,RESUMED(onResume)下一个就是STARTED(onPause);
(2)注意有两层循环,目的使所有监听者的State与被监听者一致;
(3)forwardPass逻辑跟backwardPass类似,这里就不展开说了;
(4)如果监听者被与被监听者State跨度较大,那么监听者就会经历多个dispatchEvent,例如,被监听者处于RESUMED(onResume),而被监听者已经处于(CREATED)onStop,那么监听者就会一步步走到从RESUMED到STARTED到CREATED;
(5)observer.dispatchEvent,分发envent,具体是怎么实现的,我们下一次再分析;
我们回到LifecycleRegistry.sync
private void sync() {
while (!isSynced()) {
mNewEventOccurred = false;
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;
}
(1)大家注意执行backwardPass的条件,如果集合中最早的监听器都比当前状态大,那么就执行backwardPass,集合的监听器是按状态由小到大排序的,连最小都比当前大,那么其他肯定的比当前大,所以要执行backwardPass;
(2)执行forwardPass同理;
(3)至于集合的监听器是按状态由小到大排序的,我没找到证据,只是这么猜测;
(4)循环结束条件是,最早的监听器与最后的状态一致,且最后的与当前状态一直;
补充一点(1)
LifecycleRegistry.addObserver
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;
}
......
State targetState = calculateTargetState(observer);
while ((statefulObserver.mState.compareTo(targetState) < 0
&& mObserverMap.contains(observer))) {
......
statefulObserver.dispatchEvent(lifecycleOwner, upEvent(statefulObserver.mState));
......
targetState = calculateTargetState(observer);
}
......
}
(1)将LifecycleObserver 封装成ObserverWithState ,后者包含状态以及LifecycleObserver;
(2)mObserverMap集合中有,就直接返回;
(3)mLifecycleOwner是被监听者的弱引用,这是为了防止内存泄漏;
(4)如果监听者状态小于当前状态,则需要同步,例如是在onResume方法注册监听器的,那么监听器就依次收到onCreate、onStart、onResume事件,这属于粘性操作吧;
补充一点(1)
Step 2:ReportFragment.injectIfNeededIn
public static void injectIfNeededIn(Activity activity) {
if (Build.VERSION.SDK_INT >= 29) {
// On API 29+, we can register for the correct Lifecycle callbacks directly
activity.registerActivityLifecycleCallbacks(
new LifecycleCallbacks());
}
android.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();
}
}
从代码可以看到,如果api大于29,利用Activity实现的机制做监听,注册LifecycleCallbacks,原理很简单,当Activity onCreate被触发那么LifecycleCallbacks被回调,不过注意,当Activity onCreate执行完,LifecycleCallbacks对应方法才会被回调。为了兼容旧版本,还是会添加一个Fragment,不过当api大于29,Fragment监听到的事件是不会分发的,具体就不在这展开了。
总结
(1)添加Observer,会被封装成ObserverWithState存放到集合当中,而且会将Observer同步到被监听者的当前状态;
(2)通过给Activity添加空白Fragment来监听生命周期事件;
(3)当生命周期方法变化,则通过ObserverWithState进行分发,backpass或forwardpass,例如,onResume->onPause,则是backpass,如果是onStart->onResume,则是forwardpass;
(4)事件分发会有粘性;
以上分析有不对的地方,请指出,互相学习,谢谢哦!
网友评论