JetPack之Lifecycle2.2.0源码分析
本文基于下面的依赖对Lifecycle核心源码分析
api "androidx.lifecycle:lifecycle-extensions:2.2.0" api "androidx.lifecycle:lifecycle-viewmodel-ktx:2.2.0"
1.Lifecycle的两种使用方式:
lifecycle.addObserver(object : LifecycleEventObserver { override fun onStateChanged(source: LifecycleOwner, event: Lifecycle.Event) { Log.e("tag", "${event}") if (event == Lifecycle.Event.ON_RESUME) { } } })
lifecycle.addObserver(MyObserver()) //ReflectiveGenericLifecycleObserver public class MyObserver : LifecycleObserver { @OnLifecycleEvent(Lifecycle.Event.ON_CREATE) public fun onCreate() { Log.e("tag", "MyObserver -> onCreate: "); } @OnLifecycleEvent(Lifecycle.Event.ON_START) public fun onStart() { Log.e("tag", "MyObserver -> onStart: "); } @OnLifecycleEvent(Lifecycle.Event.ON_RESUME) public fun onResume() { Log.e("tag", "MyObserver -> onResume: "); } @OnLifecycleEvent(Lifecycle.Event.ON_PAUSE) public fun onPause() { Log.e("tag", "MyObserver -> onPause: "); } @OnLifecycleEvent(Lifecycle.Event.ON_STOP) public fun onStop() { Log.e("tag", "MyObserver -> onStop: "); } @OnLifecycleEvent(Lifecycle.Event.ON_DESTROY) public fun onDestroy() { Log.e("tag", "MyObserver -> onDestroy: "); } }
1.1 生命周期的同步:
比如,我在点击按钮后添加一个addObserver
btn.setOnClickListener { //当前Activity已经属于onResume状态 lifecycle.addObserver(object : LifecycleEventObserver { override fun onStateChanged(source: LifecycleOwner, event: Lifecycle.Event) { Log.e("tag", "${event}") } }) }
当点击按钮后,输出日志如下:
也就是说,不管什么时候添加Observer,回调会从onCreate执行到activity的当前状态
1.2 重入问题:
重入问题下文的源码分析会做说明,先用代码解释下显现:
btn.setOnClickListener { //当前Activity已经属于onResume状态 lifecycle.addObserver(object : LifecycleEventObserver { override fun onStateChanged(source: LifecycleOwner, event: Lifecycle.Event) { Log.e("tag", "第一个: ${event}") if (event == Lifecycle.Event.ON_START) { //当第一个观察者执行到onStart事件后,添加第二个观察者Observer lifecycle.addObserver(object : LifecycleEventObserver { override fun onStateChanged(source: LifecycleOwner, event: Lifecycle.Event) { Log.e("tag", "第二个: ${event}") } }) } } }) }
点击按钮后,输出日志如下:
也就是说 在第一个Observer分发事件的回调中执行添加Observer后,第二个Observer的执行事件不会超过第一个Observer,具体下面会分析源码
2. Lifecycle对activity/fragment的生命周期的感知
使用ReportFragment -> injectIfNeededIn的方式,在activity中放入一个空的Fragment来代理activity的生命周期,主要包含两个地方:
1. ComponentActivity的onCreate() 方法也有调用ReportFragment.injectIfNeededIn(this);
2. ProcessLifecycleOwnerInitializer -> LifecycleDispatcher
2.1. ProcessLifecycleOwnerInitializer
public class ProcessLifecycleOwnerInitializer extends ContentProvider {
@Override
public boolean onCreate() {
LifecycleDispatcher.init(getContext());//内部注册了DispatcherActivityCallback,再
ProcessLifecycleOwner.init(getContext());//便于我们监听app前后台的运行状态
return true;
}
}
2.2 使用ProcessLifecycleOwner监听app的前后台运行状态
/** * 当应用程序从后台回到前台,或者应用程序首次打开,会依次调用Lifecycle.Event.ON_START,Lifecycle.Event.ON_RESUME。 * 当应用程序从前台退到后台(用户按下home键或任务菜单键),会依次调用Lifecycle.Event.ON_PAUSE,Lifecycle.Event.ON_STOP */ ProcessLifecycleOwner.get().lifecycle.addObserver(object : LifecycleEventObserver{ override fun onStateChanged(source: LifecycleOwner, event: Lifecycle.Event) { if(event == Lifecycle.Event.ON_START){ Log.e("tag","app进入前台了") }else if(event == Lifecycle.Event.ON_STOP){ Log.e("tag","app进入后台了") } } })
下面看下ReportFragment的相关代码
//ReportFragment public class ReportFragment extends Fragment { private static final String REPORT_FRAGMENT_TAG = "androidx.lifecycle" + ".LifecycleDispatcher.report_fragment_tag"; public static void injectIfNeededIn(Activity activity) { if (Build.VERSION.SDK_INT >= 29) { // On API 29+, 可以直接注册activity的生命周期回调 activity.registerActivityLifecycleCallbacks(new LifecycleCallbacks()); } //低于api 29的 添加一个监听生命周期的fragment到activity 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(); } } //在ReportFragment对应的生命周期的方法中调用了该分发 private void dispatch(@NonNull Lifecycle.Event event) { if (Build.VERSION.SDK_INT < 29) { //仅从在API 29之前的API级别上从ReportFragment调度事件。 //在API 29+上,这由添加到ReportFragment.injectIfNeededIn中的ActivityLifecycleCallbacks处理。 dispatch(getActivity(), event); } } //API在29以上的处理 static void dispatch(@NonNull Activity activity, @NonNull Lifecycle.Event event) { if (activity instanceof LifecycleRegistryOwner) {//给android.support.v7.app.AppCompatActivity使用的 ((LifecycleRegistryOwner) activity).getLifecycle().handleLifecycleEvent(event); return; } if (activity instanceof LifecycleOwner) { //比如androidx中的ComponentActivity实现了LifecycleOwner Lifecycle lifecycle = ((LifecycleOwner) activity).getLifecycle(); if (lifecycle instanceof LifecycleRegistry) { ((LifecycleRegistry) lifecycle).handleLifecycleEvent(event); } } } }
当我们在Activity中调用getLifecycle().addObserver()时,将LifecycleObserver转换成ObserverWithState,代码如下:
// LifecycleRegistry public void addObserver(@NonNull LifecycleObserver observer) { State initialState = mState == DESTROYED ? DESTROYED : INITIALIZED; ObserverWithState statefulObserver = new ObserverWithState(observer, initialState);
//参略下面代码 } static class ObserverWithState { State mState; LifecycleEventObserver mLifecycleObserver; ObserverWithState(LifecycleObserver observer, State initialState) { //代理生命周期变化的事件分发,将observer转换成LifecycleEventObserver 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; } } //根据不同的观察者,包装成不同的类来处理回调 static LifecycleEventObserver lifecycleEventObserver(Object object) { boolean isLifecycleEventObserver = object instanceof LifecycleEventObserver; boolean isFullLifecycleObserver = object instanceof FullLifecycleObserver; if (isLifecycleEventObserver && isFullLifecycleObserver) { return new FullLifecycleObserverAdapter((FullLifecycleObserver) object, (LifecycleEventObserver) object); } if (isFullLifecycleObserver) { return new FullLifecycleObserverAdapter((FullLifecycleObserver) object, null); } if (isLifecycleEventObserver) { return (LifecycleEventObserver) object; } //使用了注解,这里分为编译期注解和运行时注解 final Class<?> klass = object.getClass(); int type = getObserverConstructorType(klass); // 获取 type // GENERATED_CALLBACK 表示注解生成的代码 // REFLECTIVE_CALLBACK 表示使用反射 if (type == GENERATED_CALLBACK) { List<Constructor<? extends GeneratedAdapter>> constructors = sClassToAdapters.get(klass); if (constructors.size() == 1) { GeneratedAdapter generatedAdapter = createGeneratedAdapter( constructors.get(0), object); return new SingleGeneratedAdapterObserver(generatedAdapter); } GeneratedAdapter[] adapters = new GeneratedAdapter[constructors.size()]; for (int i = 0; i < constructors.size(); i++) { adapters[i] = createGeneratedAdapter(constructors.get(i), object); } return new CompositeGeneratedAdaptersObserver(adapters); } return new ReflectiveGenericLifecycleObserver(object); }
接着看添加观察者LifecycleObserver的操作分析:
//类:LifecycleRegistry public void addObserver(@NonNull LifecycleObserver observer) { State initialState = mState == DESTROYED ? DESTROYED : INITIALIZED; ObserverWithState statefulObserver = new ObserverWithState(observer, initialState); //转换成ObserverWithState后,保存到mObserverMap ObserverWithState previous = mObserverMap.putIfAbsent(observer, statefulObserver); if (previous != null) { return; //如果不为null,代表添加的observer已经添加过一次了 } LifecycleOwner lifecycleOwner = mLifecycleOwner.get(); if (lifecycleOwner == null) { // it is null we should be destroyed. Fallback quickly return; } //mAddingObserverCounter 代表当前添加的observer正在分发事件的个数,跟重入有关 boolean isReentrance = mAddingObserverCounter != 0 || mHandlingEvent; //需要分发到的状态,根据activity的当前状态与mParentStates的状态对比,选出最小的那个 State targetState = calculateTargetState(observer); mAddingObserverCounter++; while ((statefulObserver.mState.compareTo(targetState) < 0 && mObserverMap.contains(observer))) { pushParentState(statefulObserver.mState);//将当前的observer的状态保存到mParentStates statefulObserver.dispatchEvent(lifecycleOwner, upEvent(statefulObserver.mState)); popParentState();//如果当前observer的事件分发完,就移除mParentStates,跟重入有关 // mState / subling may have been changed recalculate targetState = calculateTargetState(observer); } if (!isReentrance) { // 不是重入状态,同步观察者observer的生命周期状态(里面再次执行生命周期的事件分发) sync(); } mAddingObserverCounter--; }
看了上面的代码,就可以解释文章开头的两个现象了:
1. 对生命周期的同步,当调用addObserver方法后,通过while循环,分发每一个事件,直到跟当前activity的生命周期事件一致
2. 重入问题, 当第一个Observer在执行while循环中的statefulObserver.dispatchEvent()的回调中,添加第二个Observer, 此时第二个Observer在执行while循环时,targetState 会拿第一个Observer执行到的事件状态对比,第二个Observer的事件执行不会超过第一个的,当第一个Observer的while循环执行完后,再通过sync() 方法,同步第二个Observer的事件分发
感知到activity生命周期变化到onPause()时,lifecycle的事件分发流程:
生命周期的执行与activity原本生命周期的执行顺序:
在LifecycleRegistry类的handleLifecycleEvent() 方法上打个断点,很容易看出来lifecycle生命周期改变回调的执行顺序,如下:
先看上图的最后一个箭头Activity类中的performPause()
同理,可以在activity类中看到其他生命周期方法的执行顺序与fragment的关系
接着,再看Fragment类中的fragment自身的生命周期执行与mLifecycleRegistry的生命周期执行的顺序,如下:
void performStart() { mChildFragmentManager.noteStateNotSaved(); mChildFragmentManager.execPendingActions(true); mState = STARTED; mCalled = false; onStart(); if (!mCalled) { throw new SuperNotCalledException("Fragment " + this + " did not call through to super.onStart()"); } mLifecycleRegistry.handleLifecycleEvent(Lifecycle.Event.ON_START); if (mView != null) { mViewLifecycleOwner.handleLifecycleEvent(Lifecycle.Event.ON_START); } mChildFragmentManager.dispatchStart(); } void performResume() { mChildFragmentManager.noteStateNotSaved(); mChildFragmentManager.execPendingActions(true); mState = RESUMED; mCalled = false; onResume(); if (!mCalled) { throw new SuperNotCalledException("Fragment " + this + " did not call through to super.onResume()"); } mLifecycleRegistry.handleLifecycleEvent(Lifecycle.Event.ON_RESUME); if (mView != null) { mViewLifecycleOwner.handleLifecycleEvent(Lifecycle.Event.ON_RESUME); } mChildFragmentManager.dispatchResume(); } void performStop() { mChildFragmentManager.dispatchStop(); if (mView != null) { mViewLifecycleOwner.handleLifecycleEvent(Lifecycle.Event.ON_STOP); } mLifecycleRegistry.handleLifecycleEvent(Lifecycle.Event.ON_STOP);//lifecycle的回调 mState = ACTIVITY_CREATED; mCalled = false; onStop();//fragment自身的onStop if (!mCalled) { throw new SuperNotCalledException("Fragment " + this + " did not call through to super.onStop()"); } } void performDestroyView() { mChildFragmentManager.dispatchDestroyView(); if (mView != null) { mViewLifecycleOwner.handleLifecycleEvent(Lifecycle.Event.ON_DESTROY);// 这里需要注意下,对于fragment, 可以使用fragment.viewLifecycleOwner.lifecycle.addObserver } mState = CREATED; mCalled = false; onDestroyView(); if (!mCalled) { throw new SuperNotCalledException("Fragment " + this + " did not call through to super.onDestroyView()"); } // Handles the detach/reattach case where the view hierarchy // is destroyed and recreated and an additional call to // onLoadFinished may be needed to ensure the new view // hierarchy is populated from data from the Loaders LoaderManager.getInstance(this).markForRedelivery(); mPerformedCreateView = false; } void performDestroy() { mChildFragmentManager.dispatchDestroy(); mLifecycleRegistry.handleLifecycleEvent(Lifecycle.Event.ON_DESTROY); mState = INITIALIZING; mCalled = false; mIsCreated = false; onDestroy(); if (!mCalled) { throw new SuperNotCalledException("Fragment " + this + " did not call through to super.onDestroy()"); } }
对于Fragment有个viewLifecycleOwner:
fragment.lifecycle.addObserver(object : LifecycleEventObserver{ override fun onStateChanged(source: LifecycleOwner, event: Lifecycle.Event) { } }) fragment.viewLifecycleOwner.lifecycle.addObserver(object : LifecycleEventObserver{ override fun onStateChanged(source: LifecycleOwner, event: Lifecycle.Event) { //不同点在于使用viewLifecycleOwner,在fragment执行onDestroyView之前这里会回调Lifecycle.Event.ON_DESTROY, 上面的生命周期事件分发中有说到 } })
Activity中的lifecycleScope
依赖如下
androidx.lifecycle:lifecycle-runtime-ktx:2.2.0
lifecycleScope.launch { } lifecycleScope.launchWhenResumed { } //对于Fragment: viewLifecycleOwner.lifecycleScope.launch { }