publicstaticvoidinjectIfNeededIn(Activityactivity){if(Build.VERSION.SDK_INT>=29){// On API 29+, we can register for the correct Lifecycle callbacks directly//>=29 Android Q 直接调用activity的registerActivityLifecycleCallbacks方法。//registerActivityLifecycleCallbacks方法是29新增的activity.registerActivityLifecycleCallbacks(newLifecycleCallbacks());}// 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.FragmentManagermanager=activity.getFragmentManager();if(manager.findFragmentByTag(REPORT_FRAGMENT_TAG)==null){//创建ReportFragment 并添加到Fragment中manager.beginTransaction().add(newReportFragment(),REPORT_FRAGMENT_TAG).commit();// Hopefully, we are the first to make a transaction.manager.executePendingTransactions();}}
privatevoiddispatch(@NonNullLifecycle.Eventevent){//既然>=29不调用该方法,为什么injectIfNeededIn不直接大于等于29还要添加一个ReportFragment呢?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.injectIfNeededIn//调用重载方法dispatch(getActivity(),event);}}
@OverridepublicvoidaddObserver(@NonNullLifecycleObserverobserver){//获取初始状态StateinitialState=mState==DESTROYED?DESTROYED:INITIALIZED;//创建ObserverWithStateObserverWithStatestatefulObserver=newObserverWithState(observer,initialState);//添加到FastSafeIterableMap中 //如果添加的LifecycleObserver已经存在 则直接返回存在的valueObserverWithStateprevious=mObserverMap.putIfAbsent(observer,statefulObserver);//如果已经添加过,则不重复添加直接返回if(previous!=null){return;}LifecycleOwnerlifecycleOwner=mLifecycleOwner.get();if(lifecycleOwner==null){// it is null we should be destroyed. Fallback quicklyreturn;}//正在添加Observer或者正在处理事件booleanisReentrance=mAddingObserverCounter!=0||mHandlingEvent;//计算目标状态StatetargetState=calculateTargetState(observer);//正在添加的Observer数量mAddingObserverCounter++;//如果Observer的状态小于目标状态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--;}
privatevoidmoveToState(Statenext){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;}
privatevoidsync(){LifecycleOwnerlifecycleOwner=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.//如果当前State小于链表中第一Observer的State //调用backwardPass方法后向前同步所有Observer的Sateif(mState.compareTo(mObserverMap.eldest().getValue().mState)<0){backwardPass(lifecycleOwner);}//获取链表中最后一个EntryEntry<LifecycleObserver,ObserverWithState>newest=mObserverMap.newest();//如果当前状态大于最后一个Observer的State//调用forwardPass从前向后遍历Observer同步Stateif(!mNewEventOccurred&&newest!=null&&mState.compareTo(newest.getValue().mState)>0){forwardPass(lifecycleOwner);}}mNewEventOccurred=false;}
privatestaticEventdownEvent(Statestate){switch(state){caseINITIALIZED:thrownewIllegalArgumentException();caseCREATED:returnON_DESTROY;caseSTARTED:returnON_STOP;caseRESUMED:returnON_PAUSE;caseDESTROYED:thrownewIllegalArgumentException();}thrownewIllegalArgumentException("Unexpected state value "+state);}
privatestaticintresolveObserverCallbackType(Class<?>klass){// anonymous class bug:35073837if(klass.getCanonicalName()==null){returnREFLECTIVE_CALLBACK;}//获取构造函数Constructor<?extendsGeneratedAdapter>constructor=generatedConstructor(klass)if(constructor!=null){//构造函数不为空 存入map中sClassToAdapters.put(klass,Collections.<Constructor<?extendsGeneratedAdapter>>singletonList(constructor))returnGENERATED_CALLBACK;}booleanhasLifecycleMethods=ClassesInfoCache.sInstance.hasLifecycleMethods(klasif(hasLifecycleMethods){returnREFLECTIVE_CALLBACK;}Class<?>superclass=klass.getSuperclass();List<Constructor<?extendsGeneratedAdapter>>adapterConstructors=null;if(isLifecycleParent(superclass)){if(getObserverConstructorType(superclass)==REFLECTIVE_CALLBACK){returnREFLECTIVE_CALLBACK;}adapterConstructors=newArrayList<>(sClassToAdapters.get(superclass));}for(Class<?>intrface:klass.getInterfaces()){if(!isLifecycleParent(intrface)){continue;}if(getObserverConstructorType(intrface)==REFLECTIVE_CALLBACK){returnREFLECTIVE_CALLBACK;}if(adapterConstructors==null){adapterConstructors=newArrayList<>();}adapterConstructors.addAll(sClassToAdapters.get(intrface));}if(adapterConstructors!=null){sClassToAdapters.put(klass,adapterConstructors);returnGENERATED_CALLBACK;}returnREFLECTIVE_CALLBACK;}
@NullableprivatestaticConstructor<?extendsGeneratedAdapter>generatedConstructor(Class<?>klass){try{PackageaPackage=klass.getPackage();Stringname=klass.getCanonicalName();//获取包名finalStringfullPackage=aPackage!=null?aPackage.getName():"";//获取adapterNamefinalStringadapterName=getAdapterName(fullPackage.isEmpty()?name:name.substring(fullPackage.length()+1));//获取Class对象@SuppressWarnings("unchecked")finalClass<?extendsGeneratedAdapter>aClass=(Class<?extendsGeneratedAdapter>)Class.forName(fullPackage.isEmpty()?adapterName:fullPackage+"."+adapterName);//构造函数Constructor<?extendsGeneratedAdapter>constructor=aClass.getDeclaredConstructor(klass);if(!constructor.isAccessible()){constructor.setAccessible(true);}returnconstructor;}catch(ClassNotFoundExceptione){returnnull;}catch(NoSuchMethodExceptione){// this should not happenthrownewRuntimeException(e);}}