我自己開發(fā)的一款填色小游戲, 運用到了很多android技術(shù),
歡迎大家到應用市場評論下載安琪花園
介紹Lifecycle之前,首先要明白Lifecycle的用途
監(jiān)聽Activity 和 fragment生命周期的變化
關(guān)于LifeCycle有幾個重要的類, 它們是如何串聯(lián)起來實現(xiàn)的喲
- LifecycleObserver
- LifeCycleOwner
- Lifecycle
- LifecycleRegistry
先看一張這個圖,從這張圖里面能夠看到activity 和 fragment里面都有生命周期方法的處理。
因此要看懂lifeCycle 的原理,可以從這幾個方法出發(fā)。

image.png
第一步: lifeCycle如何使用
getLifecycle().addObserver(new CustomLifecycle());
// 觀察者角色
// 監(jiān)聽Activity/Fragment 所有生命周期函數(shù)
public class CustomLifecycle implements LifecycleObserver {
private static final String TAG = CustomLifecycle.class.getSimpleName();
// 監(jiān)聽 onCreate 生命時候被執(zhí)行
@OnLifecycleEvent(Lifecycle.Event.ON_CREATE)
public void onCreateMethod() {
Log.d(TAG, "onCreate生命周期函數(shù)執(zhí)行了...");
}
// 監(jiān)聽 onStart 生命時候被執(zhí)行
@OnLifecycleEvent(Lifecycle.Event.ON_START)
public void onStartMethod() {
Log.d(TAG, "onStart生命周期函數(shù)執(zhí)行了...");
}
// 監(jiān)聽 onStop 生命時候被執(zhí)行
@OnLifecycleEvent(Lifecycle.Event.ON_STOP)
public void onStopMethod() {
Log.d(TAG, "onStop生命周期函數(shù)執(zhí)行了...");
}
// 監(jiān)聽 onResume 生命時候被執(zhí)行
@OnLifecycleEvent(Lifecycle.Event.ON_RESUME)
public void onResumeMethod() {
Log.d(TAG, "onResume生命周期函數(shù)執(zhí)行了...");
}
// 監(jiān)聽 onResume 生命時候被執(zhí)行
@OnLifecycleEvent(Lifecycle.Event.ON_PAUSE)
public void onPauseMethod() {
Log.d(TAG, "onPause生命周期函數(shù)執(zhí)行了...");
}
// 監(jiān)聽 onDestroy 生命時候被執(zhí)行
@OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
public void onDestroyMethod() {
Log.d(TAG, "onDestroy生命周期函數(shù)執(zhí)行了...");
}
}
這樣當activity或者Fragment里面的生命周期發(fā)生變化就會執(zhí)行相應的方法。
第二步, 如果稍微動一下腦筋,應該能夠猜到, 調(diào)用handleLifecycleEvent方法,最后肯定都是通過獲取注解,反射調(diào)用相應的方法。
注冊觀察者的時候做了些什么操作

image.png
注冊的Observer會包裝成ObserverWithState并保存到一個map里面。
static class ObserverWithState {
State mState;
LifecycleEventObserver mLifecycleObserver;
ObserverWithState(LifecycleObserver observer, State initialState) {
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;
}
}
接下來著重看一下是如何執(zhí)行到了Observer里面的onStateChange方法
handleLifecycleEvent ——> moveToState ——> sync ——> forwardPass
當生命周期變化后會執(zhí)行這一系列的方法
最終會調(diào)用到
observer.dispatchEvent(lifecycleOwner, upEvent(observer.mState));
這個方法最終就會調(diào)用到observer.onStateChange方法
思考
現(xiàn)在官方的Lifecycle只能在Activity 和Fragment中使用, 如果想在RecycleView的Holder中也使用LifeCycle? 那應該如何去實現(xiàn)呢?
發(fā)散一下大家的思維