到官方文档下看 Google Lifecycle,Lifecycle的作用是:生命周期感知型组件可执行操作来响应另一个组件(如 Activity 和 Fragment)的生命周期状态的变化。这些组件有助于您写出更有条理且往往更精简的代码,这样的代码更易于维护。
我们之前开发,因为Activity 或者是 Fragment 的生命周期问题而间接引起的内存问题挺多的,比如每次都要写资源,或者控件工具的回收释放,如果忘记写了,那么可能会引起内存泄漏,而现在搭配 Lifecycle,给我们生命周期的回调,就不必再像以前在某个生命周期加上逻辑代码,而是直接提前写对应的代码,更好解决生命周期问题。
override fun onPause(){super.onPause()Log.d(TAG,"onPause")}
override fun onStop(){super.onStop()Log.d(TAG,"onStop")}
override fun onStart(){super.onStart()Log.d(TAG,"onStart")}
override fun onResume(){super.onResume()Log.d(TAG,"onResume")}
override fun onRestart(){super.onRestart()Log.d(TAG,"onRestart")}
override fun onDestroy(){super.onDestroy()Log.d(TAG,"onDestroy")}
/* ReportFragment */publicstaticvoidinjectIfNeededIn(Activity activity){if(Build.VERSION.SDK_INT >=29){// On API 29+, we can register for the correct Lifecycle callbacks directlyLifecycleCallbacks.registerIn(activity);}// Prior to API 29 and to maintain compatibility with older versions of// ProcessLifecycleOwner (which may not be updated when lifecycle-runtime is updated and// need to support activities that don't extend from FragmentActivity from support lib),// use a framework fragment to get the correct timing of Lifecycle eventsandroid.app.FragmentManager manager = activity.getFragmentManager();if(manager.findFragmentByTag(REPORT_FRAGMENT_TAG)==null){
manager.beginTransaction().add(newReportFragment(), REPORT_FRAGMENT_TAG).commit();// Hopefully, we are the first to make a transaction.
manager.executePendingTransactions();}}
反正无论是使用 LifecycleCallbacks.registerIn(activity),还是 Fragment 的生命周期回调,最后都会dispatch。
@OverridepublicvoidonActivityCreated(Bundle savedInstanceState){super.onActivityCreated(savedInstanceState);dispatchCreate(mProcessListener);dispatch(Lifecycle.Event.ON_CREATE);}privatevoiddispatch(@NonNullLifecycle.Event event){if(Build.VERSION.SDK_INT <29){// Only dispatch events from ReportFragment on API levels prior// to API 29. On API 29+, this is handled by the ActivityLifecycleCallbacks// added in ReportFragment.injectIfNeededIndispatch(getActivity(), event);}}staticvoiddispatch(@NonNullActivity activity,@NonNullLifecycle.Event event){if(activity instanceofLifecycleRegistryOwner){((LifecycleRegistryOwner) activity).getLifecycle().handleLifecycleEvent(event);return;}if(activity instanceofLifecycleOwner){Lifecycle lifecycle =((LifecycleOwner) activity).getLifecycle();if(lifecycle instanceofLifecycleRegistry){((LifecycleRegistry) lifecycle).handleLifecycleEvent(event);}}}
/* Lifecycle.Event */@NonNullpublicStategetTargetState(){switch(this){case ON_CREATE:case ON_STOP:returnState.CREATED;case ON_START:case ON_PAUSE:returnState.STARTED;case ON_RESUME:returnState.RESUMED;case ON_DESTROY:returnState.DESTROYED;case ON_ANY:break;}thrownewIllegalArgumentException(this+" has no target state");}
将 Lifecycle.State 继续往下传,先用 mState 保存,再 sync 方法处理。
/* LifecycleRegistry */publicvoidhandleLifecycleEvent(@NonNullLifecycle.Event event){enforceMainThreadIfNeeded("handleLifecycleEvent");moveToState(event.getTargetState());}privatevoidmoveToState(State next){if(mState == next){return;}//保存state状态
mState = next;if(mHandlingEvent || mAddingObserverCounter !=0){
mNewEventOccurred =true;// we will figure out what to do on upper level.return;}
mHandlingEvent =true;sync();
mHandlingEvent =false;}
3.10 sync
这里利用上一个方法保存的mState,用于比较,判断是正向执行还是反向执行生命周期。
/* LifecycleRegistry */privatevoidsync(){//这是弱引用包装过的LifecycleOwner LifecycleOwner lifecycleOwner = mLifecycleOwner.get();if(lifecycleOwner ==null){thrownewIllegalStateException("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.//上一个方法保存的mState,跟组件之前的的mState对比if(mState.compareTo(mObserverMap.eldest().getValue().mState)<0){//返向执行流程backwardPass(lifecycleOwner);}Map.Entry<LifecycleObserver,ObserverWithState> newest = mObserverMap.newest();if(!mNewEventOccurred && newest !=null&& mState.compareTo(newest.getValue().mState)>0){//正向执行流程forwardPass(lifecycleOwner);}}
mNewEventOccurred =false;}