您總說夢想遙不可及马胧,可您卻從不早睡汉买。也不早起——《狼道》
目錄
一、前言
二佩脊、源碼分析
(1)添加觀察者
(2)通知觀察者
(3)何時通知
三蛙粘、總結(jié)
四、內(nèi)容推薦
五威彰、項目參考
一出牧、前言
——回顧了一下之前學習過的東西并打算把這些東西整理成文章,加深映像和理解抱冷,同時也傳達自己的見解供大家參考崔列,若存在錯誤或不足的地方梢褐,希望您能指出旺遮。
本篇續(xù)《Android Jetpack架構(gòu)組件之Lifecycle入門》文章之后赵讯,上一篇介紹了Lifecycle。由于篇幅太長拆成兩篇耿眉。這篇主要是分析Lifecycle源碼边翼,理解其實現(xiàn)原理忍级〖帕幔回顧一下Lifecycle結(jié)構(gòu)圖
LifeCycle相關(guān)鏈接——官方文檔步淹、接口文檔赏陵、相關(guān)依賴文檔
二赤拒、源碼分析
——通過上面的使用過程敌蜂,大體理解為創(chuàng)建一個觀察者捌木,當組件生命周期發(fā)生變化時庸论,通知觀察者有LifeCycle注解的方法做出響應(yīng)铛纬。那么實現(xiàn)原理分成兩部分來分析
(1)怎么通知觀察者響應(yīng)生命周期的變化(怎么通知)
(2)生命周期更改的時候是如何通知觀察者的(何時通知)
(1)添加觀察者
1.使用入口 getLifecycle().addObserver() (不同版本Lifecycle源碼各有差異厌均,這邊引用的是'androidx.appcompat:appcompat:1.1.0)
/*
* 通過查看源碼得出MainActivity繼承了AppCompatActivity,AppCompatActivity繼承了FragmentActivity 告唆,F(xiàn)ragmentActivity 繼ComponentActivity
* 并實現(xiàn)了LifecycleOwner接口的getLifecycle()方法 棺弊,返回生命周期的提供者 ,而FragmentActivity重寫了ComponentActivity的getLifecycle()方法
* 所以這邊調(diào)用的是FragmentActivity里面的getLifecycle()方法得到LifecycleRegistry實例
*/
final LifecycleRegistry mFragmentLifecycleRegistry = new LifecycleRegistry(this);
public Lifecycle getLifecycle() {
//這里返回LifecycleRegistry對象
return mFragmentLifecycleRegistry;
}
2.FragmentActivity里面創(chuàng)建了LifecycleRegistry 實例擒悬,下面看下LifecycleRegistry構(gòu)造源碼
// 給生命周期的提供者創(chuàng)建一個LifecycleRegistry
public LifecycleRegistry(@NonNull LifecycleOwner provider) {
mLifecycleOwner = new WeakReference<>(provider);
mState = INITIALIZED;
}
3.LifecycleRegistry繼承了Lifecycle抽象類模她,并重寫了addObserver()方法。主要作用是添加一個生命周期的觀察者懂牧,當生命周期的提供者發(fā)生狀態(tài)改變的時候侈净,通知觀察者做出響應(yīng)
//保存觀察者的自定義列表
private FastSafeIterableMap<LifecycleObserver, ObserverWithState> mObserverMap =
new FastSafeIterableMap<>();
@Override
public void addObserver(@NonNull LifecycleObserver observer) {
//設(shè)置lifecycle的初始狀態(tài) ,State是個生命周期的枚舉類型
State initialState = mState == DESTROYED ? DESTROYED : INITIALIZED;
//創(chuàng)建ObserverWithState實例僧凤,并將LifecycleObserver 轉(zhuǎn)化為LifecycleEventObserver用狱,詳情看(4)
ObserverWithState statefulObserver = new ObserverWithState(observer, initialState);
//保存生命周期的觀察者與ObserverWithState(觀察者的生命狀態(tài)),保存成功返回NULL拼弃,否則說明已經(jīng)保存過夏伊,返回ObserverWithState對象
ObserverWithState previous = mObserverMap.putIfAbsent(observer, statefulObserver);
//攔截已經(jīng)保存過的觀察者
if (previous != null) {
return;
}
//生命周期的提供者被回收則返回不繼續(xù)執(zhí)行
LifecycleOwner lifecycleOwner = mLifecycleOwner.get();
if (lifecycleOwner == null) {
return;
}
// 判斷是否連續(xù)添加了觀察者 或者 正在處理事件 是返回true
boolean isReentrance = mAddingObserverCounter != 0 || mHandlingEvent;
//獲取狀態(tài) 詳情看(5)
State targetState = calculateTargetState(observer);
//正在添加的觀察者數(shù)量+1
mAddingObserverCounter++;
//如果觀察者生命周期狀態(tài)比前面添加進來的小,說明生命周期發(fā)生變化吻氧,執(zhí)行以下步驟
//比如: onCreate()方法中與onResume()方法中同時調(diào)用了 addObserver()方法
while ((statefulObserver.mState.compareTo(targetState) < 0
&& mObserverMap.contains(observer))) {
//存儲添加進來的觀察者狀態(tài)溺忧,詳情看(7)
pushParentState(statefulObserver.mState);
//分發(fā)事件 dispatchEvent詳情看(4) upEvent詳情看(8)
statefulObserver.dispatchEvent(lifecycleOwner, upEvent(statefulObserver.mState));
//移除最后一個添加進去的觀察者,詳情看(7)
popParentState();
//獲取狀態(tài) 詳情看(5)
targetState = calculateTargetState(observer);
}
// 當isReentrance為false時 進行同步
if (!isReentrance) {
// we do sync only on the top level.
sync();
}
//添加完成時正在處理的觀察者數(shù)量減一
mAddingObserverCounter--;
}
4.ObserverWithState主要是將LifecycleObserver 轉(zhuǎn)化為LifecycleEventObserver
//將LifecycleObserver 轉(zhuǎn)化為LifecycleEventObserver
static class ObserverWithState {
State mState;
LifecycleEventObserver mLifecycleObserver;
//將LifecycleObserver 轉(zhuǎn)化為LifecycleEventObserver
ObserverWithState(LifecycleObserver observer, State initialState) {
//lifecycleEventObserver將LifecycleObserver 轉(zhuǎn)化成LifecycleEventObserver
mLifecycleObserver = Lifecycling.lifecycleEventObserver(observer);
mState = initialState;
}
//將生命周期的提供者與Event
void dispatchEvent(LifecycleOwner owner, Event event) {
//獲取生命周期狀態(tài)
State newState = getStateAfter(event);
//對比兩個狀態(tài)
mState = min(mState, newState);
//在發(fā)生生命周期狀態(tài)轉(zhuǎn)換事件時調(diào)用 FullLifecycleObserverAdapter實現(xiàn)了LifecycleEventObserver接口的該方法
mLifecycleObserver.onStateChanged(owner, event);
mState = newState;
}
}
5.給定觀察者對比觀察者列表前后的生命周期狀態(tài)盯孙,calculateTargetState返回State最小的生命周期狀態(tài)
private State calculateTargetState(LifecycleObserver observer) {
//返回前一個觀察者的保存節(jié)點
Entry<LifecycleObserver, ObserverWithState> previous = mObserverMap.ceil(observer);
//獲取前一個觀察者的生命周期狀態(tài)鲁森,若無前一個觀察者則返null
State siblingState = previous != null ? previous.getValue().mState : null;
//獲取上一個保存的生命周期狀態(tài)
State parentState = !mParentStates.isEmpty() ? mParentStates.get(mParentStates.size() - 1): null;
//返回State更小的生命周期狀態(tài) 詳情請看(6)
return min(min(mState, siblingState), parentState);
}
6.min() 對比兩個生命周期狀態(tài),返回State更小的周期值
static State min(@NonNull State state1, @Nullable State state2) {
return state2 != null && state2.compareTo(state1) < 0 ? state2 : state1;
}
7.pushParentState保存生命周期狀態(tài) popParentState移除最后一個狀態(tài)(最后一個添加進來的值)
private ArrayList<State> mParentStates = new ArrayList<>();
private void pushParentState(State state) {
mParentStates.add(state);
}
private void popParentState() {
mParentStates.remove(mParentStates.size() - 1);
}
8.upEvent 根據(jù)生命周期狀態(tài) 返回對應(yīng)的Event 值
private static Event upEvent(State state) {
switch (state) {
case INITIALIZED:
case DESTROYED:
return ON_CREATE;
case CREATED:
return ON_START;
case STARTED:
return ON_RESUME;
case RESUMED:
throw new IllegalArgumentException();
}
throw new IllegalArgumentException("Unexpected state value " + state);
}
9.sync()同步生命周期狀態(tài)
//同步生命周期狀態(tài)
private void sync() {
//判斷生命周期是否已經(jīng)被回收
LifecycleOwner lifecycleOwner = mLifecycleOwner.get();
if (lifecycleOwner == null) {
throw new IllegalStateException("LifecycleOwner of this LifecycleRegistry is already"
+ "garbage collected. It is too late to change lifecycle state.");
}
//生命周期非同步狀態(tài)時執(zhí)行 詳情看(10)
while (!isSynced()) {
mNewEventOccurred = false;
// 當前生命周期狀態(tài)小于最早添加進來的觀察者生命周期狀態(tài)時 調(diào)用backwardPass()
if (mState.compareTo(mObserverMap.eldest().getValue().mState) < 0) {
//遍歷觀察者集合 振惰,不一致時分發(fā)事件 詳情看(12)
backwardPass(lifecycleOwner);
}
//獲取觀察者集合最新添加進來的條目
Entry<LifecycleObserver, ObserverWithState> newest = mObserverMap.newest();
// 當前生命周期狀態(tài)大于最新添加進來的觀察者生命周期狀態(tài)時 調(diào)用forwardPass() 詳情看(11)
if (!mNewEventOccurred && newest != null
&& mState.compareTo(newest.getValue().mState) > 0) {
//遍歷觀察者集合歌溉,當觀察者生命周期狀態(tài)小于當前生命周期狀態(tài)時 分發(fā)事件
forwardPass(lifecycleOwner);
}
}
mNewEventOccurred = false;
}
10.isSynced()返回當前生命周期狀態(tài)是否一致
//返回當前生命狀態(tài)是否一致 不相同為false
private boolean isSynced() {
//沒有觀察者時返回true
if (mObserverMap.size() == 0) {
return true;
}
//獲取最先添加進來的觀察者生命周期狀態(tài)
State eldestObserverState = mObserverMap.eldest().getValue().mState;
//獲取最后(最近)添加進來的觀察者生命周期狀態(tài)
State newestObserverState = mObserverMap.newest().getValue().mState;
//如果最先的和最后的Observer的狀態(tài)不一致或者當前的狀態(tài)和最新的狀態(tài)不一致時,那么需要進行狀態(tài)同步
return eldestObserverState == newestObserverState && mState == newestObserverState;
}
11.forwardPass() 遍歷觀察者集合,當觀察者生命周期狀態(tài)小于當前生命周期狀態(tài)時 分發(fā)事件
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();
//觀察者生命周期狀態(tài)小于當前生命周期狀態(tài)時 分發(fā)事件
while ((observer.mState.compareTo(mState) < 0 && !mNewEventOccurred
&& mObserverMap.contains(entry.getKey()))) {
pushParentState(observer.mState);
observer.dispatchEvent(lifecycleOwner, upEvent(observer.mState));
popParentState();
}
}
}
12.backwardPass() 遍歷觀察者集合痛垛,當觀察者生命周期狀態(tài)大于當前生命周期狀態(tài)時 分發(fā)事件
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();
//觀察者生命周期狀態(tài)大于當前生命周期狀態(tài)時 分發(fā)事件
while ((observer.mState.compareTo(mState) > 0 && !mNewEventOccurred
&& mObserverMap.contains(entry.getKey()))) {
Event event = downEvent(observer.mState);
pushParentState(getStateAfter(event));
observer.dispatchEvent(lifecycleOwner, event);
popParentState();
}
}
}
小結(jié):
- 創(chuàng)建了一個ObserverWithState實例草慧,將LifecycleObserver 轉(zhuǎn)化為LifecycleEventObserver。并封裝了一個分發(fā)事件匙头。
- 保存觀察者與對應(yīng)的ObserverWithState漫谷。
- 如果觀察者未保存過或生命周期提供者未被回收則繼續(xù)執(zhí)行
- 如果觀察者生命周期狀態(tài)比前面添加進來的小,說明生命周期發(fā)生變化蹂析。
- 存儲觀察者生命狀態(tài)后分發(fā)事件舔示,分發(fā)完成后移除保存的觀察者狀態(tài)
- 如果正在添加觀察者的數(shù)量只有1個且沒有相關(guān)的處理事件則同步生命周期狀態(tài)
到這里并沒有完,才剛開始...电抚。剛分析完添加觀察者的源碼惕稻,下一步分析是如何通知觀察者的。
(2)通知觀察者
1.從ObserverWithState類的Lifecycling.lifecycleEventObserver(observer)方法說起蝙叛,這一步是將LifecycleObserver轉(zhuǎn)化為LifecycleEventObserver那么具體如何轉(zhuǎn)化看下源碼
// 利用反射獲取LifecycleObserver的信息缩宜,創(chuàng)建一個類實現(xiàn)LifecycleEventObserver接口。并返回該類的實例
@NonNull
static LifecycleEventObserver lifecycleEventObserver(Object object) {
// instanceof是判斷其左邊對象是否為其右邊類的實例 以下都返回false
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();
//利用反射getObserverConstructorType方法根據(jù)不同情況反饋回來不同的類型 詳情看(2)
int type = getObserverConstructorType(klass);
//GENERATED_CALLBACK 表示有APT生成的觀察者適配器甥温,則執(zhí)行下面方法
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);
}
//若不是創(chuàng)建下面實例實現(xiàn)LifecycleEventObserver接口 詳情看(10)
return new ReflectiveGenericLifecycleObserver(object);
}
2.lifecycleEventObserver()判斷集合中是否有緩存觀察者對應(yīng)的反饋類型 否則通過resolveObserverCallbackType()方法獲取
private static int getObserverConstructorType(Class<?> klass) {
//如果觀察者的類已保存則返回指定鍵映射到的值
Integer callbackCache = sCallbackCache.get(klass);
if (callbackCache != null) {
return callbackCache;
}
//resolveObserverCallbackType()根據(jù)觀察者的信息反饋回不同的類型 詳情看(3)
int type = resolveObserverCallbackType(klass);
//把觀察者的類和type以鍵值對的形式保存在集合中
sCallbackCache.put(klass, type);
return type;
}
3.resolveObserverCallbackType()根據(jù)觀察者的信息返回不同的類型
private static int resolveObserverCallbackType(Class<?> klass) {
// 若基礎(chǔ)類的規(guī)范名稱為null 返回REFLECTIVE_CALLBACK
if (klass.getCanonicalName() == null) {
return REFLECTIVE_CALLBACK;
}
// 獲取觀察者適配類的構(gòu)造函數(shù)
Constructor<? extends GeneratedAdapter> constructor = generatedConstructor(klass);
if (constructor != null) {
// 把觀察者的類和適配類的構(gòu)造函數(shù)列表以鍵值對的形式保存在集合中
sClassToAdapters.put(klass, Collections
.<Constructor<? extends GeneratedAdapter>>singletonList(constructor));
return GENERATED_CALLBACK;
}
//判斷該觀察者是否有監(jiān)聽生命周期的方法 查看詳情(6)
boolean hasLifecycleMethods = ClassesInfoCache.sInstance.hasLifecycleMethods(klass);
if (hasLifecycleMethods) {
return REFLECTIVE_CALLBACK;
}
Class<?> superclass = klass.getSuperclass();
List<Constructor<? extends GeneratedAdapter>> adapterConstructors = null;
//判斷是否是LifecycleObserver
if (isLifecycleParent(superclass)) {
if (getObserverConstructorType(superclass) == REFLECTIVE_CALLBACK) {
return REFLECTIVE_CALLBACK;
}
adapterConstructors = new ArrayList<>(sClassToAdapters.get(superclass));
}
for (Class<?> intrface : klass.getInterfaces()) {
if (!isLifecycleParent(intrface)) {
continue;
}
if (getObserverConstructorType(intrface) == REFLECTIVE_CALLBACK) {
return REFLECTIVE_CALLBACK;
}
if (adapterConstructors == null) {
adapterConstructors = new ArrayList<>();
}
adapterConstructors.addAll(sClassToAdapters.get(intrface));
}
if (adapterConstructors != null) {
sClassToAdapters.put(klass, adapterConstructors);
return GENERATED_CALLBACK;
}
return REFLECTIVE_CALLBACK;
}
4.generatedConstructor(),利用反射獲取到觀察者的信息锻煌,通過信息組成的名字獲取到觀察者的適配類。返回該類的構(gòu)造函數(shù)
@Nullable
private static Constructor<? extends GeneratedAdapter> generatedConstructor(Class<?> klass) {
try {
//利用反射可以獲取到類的信息
Package aPackage = klass.getPackage();
String name = klass.getCanonicalName();
//獲取包名
final String fullPackage = aPackage != null ? aPackage.getName() : "";
//創(chuàng)建一個適配器名稱 詳情看(5)
final String adapterName = getAdapterName(fullPackage.isEmpty() ? name :
name.substring(fullPackage.length() + 1));
//加載指定名稱的類
@SuppressWarnings("unchecked") final Class<? extends GeneratedAdapter> aClass =
(Class<? extends GeneratedAdapter>) Class.forName(
fullPackage.isEmpty() ? adapterName : fullPackage + "." + adapterName);
//獲取類的構(gòu)造函數(shù)
Constructor<? extends GeneratedAdapter> constructor =
aClass.getDeclaredConstructor(klass);
//設(shè)置標志
if (!constructor.isAccessible()) {
constructor.setAccessible(true);
}
return constructor;
} catch (ClassNotFoundException e) {
return null;
} catch (NoSuchMethodException e) {
// this should not happen
throw new RuntimeException(e);
}
}
5.getAdapterName()創(chuàng)建一個適配器名稱
public static String getAdapterName(String className) {
return className.replace(".", "_") + "_LifecycleAdapter";
}
6.ClassesInfoCache.sInstance.hasLifecycleMethods(klass)姻蚓,判斷該觀察者是否有監(jiān)聽生命周期的方法
//創(chuàng)建一個緩存類
static ClassesInfoCache sInstance = new ClassesInfoCache();
boolean hasLifecycleMethods(Class klass) {
//判斷傳入的觀察者類是否已經(jīng)緩存過
Boolean hasLifecycleMethods = mHasLifecycleMethods.get(klass);
if (hasLifecycleMethods != null) {
return hasLifecycleMethods;
}
//獲取所有觀察者的公開方法
Method[] methods = getDeclaredMethods(klass);
for (Method method : methods) {
//獲取方法的注解信息
OnLifecycleEvent annotation = method.getAnnotation(OnLifecycleEvent.class);
if (annotation != null) {
// createInfo()獲取CallbackInfo實例 查看詳情(7)
createInfo(klass, methods);
return true;
}
}
mHasLifecycleMethods.put(klass, false);
return false;
}
7.createInfo()獲取CallbackInfo實例宋梧。通過declaredMethods獲取觀察者監(jiān)聽生命周期的方法,利用反射持有這些方法的引用并封裝在CallbackInfo類中
private CallbackInfo createInfo(Class klass, @Nullable Method[] declaredMethods) {
//獲取觀察者的父類LifecycleObserver
Class superclass = klass.getSuperclass();
Map<MethodReference, Lifecycle.Event> handlerToEvent = new HashMap<>();
if (superclass != null) {
//從集合獲取CallbackInfo 詳情看(8)
CallbackInfo superInfo = getInfo(superclass);
if (superInfo != null) {
handlerToEvent.putAll(superInfo.mHandlerToEvent);
}
}
//返回一個數(shù)組狰挡,其中包含表示該類實現(xiàn)的所有接口的對象
Class[] interfaces = klass.getInterfaces();
for (Class intrfc : interfaces) {
for (Map.Entry<MethodReference, Lifecycle.Event> entry : getInfo(
intrfc).mHandlerToEvent.entrySet()) {
//verifyAndPutHandler()保存保存了方法的引用與生命周期的事件類型 查看詳情(9)
verifyAndPutHandler(handlerToEvent, entry.getKey(), entry.getValue(), klass);
}
}
Method[] methods = declaredMethods != null ? declaredMethods : getDeclaredMethods(klass);
boolean hasLifecycleMethods = false;
//遍歷所有公共方法
for (Method method : methods) {
//獲取方法的注解信息
OnLifecycleEvent annotation = method.getAnnotation(OnLifecycleEvent.class);
if (annotation == null) {
continue;
}
//說明該觀察者有監(jiān)聽生命周期的方法
hasLifecycleMethods = true;
Class<?>[] params = method.getParameterTypes();
int callType = CALL_TYPE_NO_ARG;
//若方法帶有參數(shù)則判斷第一個參數(shù)是否是屬于LifecycleOwner的 否則拋出無效參數(shù)異常
if (params.length > 0) {
callType = CALL_TYPE_PROVIDER;
if (!params[0].isAssignableFrom(LifecycleOwner.class)) {
throw new IllegalArgumentException(
"invalid parameter type. Must be one and instanceof LifecycleOwner");
}
}
//獲取Lifecycle.Event
Lifecycle.Event event = annotation.value();
//判斷第二個參數(shù)是不是一個Event或On_ANY類型 否則拋出異常
if (params.length > 1) {
callType = CALL_TYPE_PROVIDER_WITH_EVENT;
if (!params[1].isAssignableFrom(Lifecycle.Event.class)) {
throw new IllegalArgumentException(
"invalid parameter type. second arg must be an event");
}
if (event != Lifecycle.Event.ON_ANY) {
throw new IllegalArgumentException(
"Second arg is supported only for ON_ANY value");
}
}
//參數(shù)超過2個拋出異常
if (params.length > 2) {
throw new IllegalArgumentException("cannot have more than 2 params");
}
//MethodReference類利用反射捂龄,封裝了一個把參數(shù)傳遞到公共方法的函數(shù)
MethodReference methodReference = new MethodReference(callType, method);
//verifyAndPutHandler()保存了方法的引用與生命周期的事件類型 查看詳情(9)
verifyAndPutHandler(handlerToEvent, methodReference, event, klass);
}
//創(chuàng)建一個CallbackInfo實例,CallbackInfo存儲著生命周期方法的引用與對應(yīng)的Lifecycle.Event
CallbackInfo info = new CallbackInfo(handlerToEvent);
//保存CallbackInfo實例
mCallbackMap.put(klass, info);
//保存方法引用
mHasLifecycleMethods.put(klass, hasLifecycleMethods);
return info;
}
8.getInfo()從集合中獲取CallbackInfo對象加叁,若未存儲則從createInfo獲取
CallbackInfo getInfo(Class klass) {
//若CallbackInfo是否已經(jīng)存儲過 則返回CallbackInfo對象
CallbackInfo existing = mCallbackMap.get(klass);
if (existing != null) {
return existing;
}
//未存儲則重新執(zhí)行createInfo
existing = createInfo(klass, null);
return existing;
}
9.verifyAndPutHandler()保存保存了方法的引用與生命周期的事件類型
private void verifyAndPutHandler(Map<MethodReference, Lifecycle.Event> handlers,
MethodReference newHandler, Lifecycle.Event newEvent, Class klass) {
//判斷newHandler倦沧,newEvent是否已經(jīng)保存過
Lifecycle.Event event = handlers.get(newHandler);
if (event != null && newEvent != event) {
Method method = newHandler.mMethod;
throw new IllegalArgumentException(
"Method " + method.getName() + " in " + klass.getName()
+ " already declared with different @OnLifecycleEvent value: previous"
+ " value " + event + ", new value " + newEvent);
}
if (event == null) {
handlers.put(newHandler, newEvent);
}
}
10.ReflectiveGenericLifecycleObserver實現(xiàn)了LifecycleEventObserver接口的onStateChanged方法,通過CallbackInfo實例拿到了觀察者中監(jiān)聽生命周期方法的引用它匕。利用反射執(zhí)行了方法展融。所以外部通過調(diào)用LifecycleEventObserver.onStateChanged的方法通知了觀察者
class ReflectiveGenericLifecycleObserver implements LifecycleEventObserver {
private final Object mWrapped;
private final CallbackInfo mInfo;
ReflectiveGenericLifecycleObserver(Object wrapped) {
mWrapped = wrapped;
mInfo = ClassesInfoCache.sInstance.getInfo(mWrapped.getClass());
}
@Override
public void onStateChanged(LifecycleOwner source, Event event) {
//調(diào)用了ClassesInfoCache的invokeCallbacks方法,該方法利用反射調(diào)用了觀察者的對應(yīng)方法
mInfo.invokeCallbacks(source, event, mWrapped);
}
}
小結(jié):
- 通過LifecycleObserver(觀察者)實例得到class豫柬,利用反射從class中獲取觀察者的所有公共方法告希,通過方法獲取到該方法注解信息
- 利用反射從方法中得到方法的引用,并將所有方法的引用與注解信息中的Lifecycle.Event一起緩存起來封裝到ClassesInfoCache中烧给。
- 創(chuàng)建ReflectiveGenericLifecycleObserver類實現(xiàn)了LifecycleEventObserver接口onStateChanged方法燕偶。該方法通過CallbackInfo實例拿到了觀察者中監(jiān)聽生命周期方法的引用并執(zhí)行。
- 外部調(diào)用onStateChanged()方法,來執(zhí)行觀察者中監(jiān)聽生命周期的方法础嫡。
(3)何時通知
1.為何Activity生命周期方法發(fā)生變化時指么,觀察者可以做出相同的響應(yīng)。主要是在FragmentActivity各個生命周期方法都調(diào)用了LifecycleRegistry.handleLifecycleEvent(Lifecycle.Event event)方法,下面我們看下源碼
//設(shè)置當前狀態(tài)并通知觀察者
public void handleLifecycleEvent(@NonNull Lifecycle.Event event) {
//獲取Lifecycle的state
State next = getStateAfter(event);
//調(diào)用了 sync()同步生命周期狀態(tài)并發(fā)送通知 查看詳情(2)
moveToState(next);
}
2.moveToState()調(diào)用了 sync()同步生命周期狀態(tài)并發(fā)送通知
private void moveToState(State next) {
//當前狀態(tài)與參數(shù)狀態(tài)相同時返回
if (mState == next) {
return;
}
//更改當前狀態(tài)
mState = next;
//正在執(zhí)行操作
if (mHandlingEvent || mAddingObserverCounter != 0) {
mNewEventOccurred = true;
// we will figure out what to do on upper level.
return;
}
mHandlingEvent = true;
//當生命周期狀態(tài)不同將必要的事件分派給觀察者伯诬,并同步生命周期狀態(tài)
sync();
mHandlingEvent = false;
}
三晚唇、總結(jié)
簡單的敘述源碼實現(xiàn)的總體流程,按照使用的步驟順序敘述:
- 創(chuàng)建一個觀察者實現(xiàn)LifecycleObserver接口姑廉,用于監(jiān)聽響應(yīng)被觀察者生命周期的變化。
- 觀察者通過注解的方式監(jiān)聽組件某個生命狀態(tài)的改變翁涤。
- LifecycleRegistry繼承了Lifecycle桥言,管理著觀察者。
- 通過LifecycleRegistry添加觀察者葵礼,利用反射原理獲取到觀察者中的方法與注解信息
- 被觀察者(組件)通過實現(xiàn)LifecycleOwner 接口拿到LifecycleRegistry
- 在組件生命周期中調(diào)用LifecycleRegistry提供的方法來監(jiān)聽生命周期狀態(tài)
- 當生命周期發(fā)生變化時号阿,LifecycleRegistry就會執(zhí)行通過反射獲取到的方法。實現(xiàn)監(jiān)聽的目的
這邊只算粗俗簡單的總結(jié)一下鸳粉,寫的詳情又感覺是在重復扔涧。具體還請看源碼 ,都有詳細注釋届谈。
建議:自己去看一遍源碼枯夜,比別人分析理解的會更痛徹。不懂的再參考本文
四艰山、內(nèi)容推薦
五湖雹、項目參考
Demo例子鑲嵌到下面Demo中
若您發(fā)現(xiàn)文章中存在錯誤或不足的地方,希望您能指出曙搬!