文章目錄
- 1.Lifecycle了解
- 2.生命周期獲取對比
- 2.1 之前的生命周期獲取
- 2.2 Lifecycle回呼生命周期
- 3.原始碼分析
- 3.1 類關系圖
- 3.2 ComponentActvitiy.onCreate
- 3.3 getLifecycle方法
- 3.4 Lifecycle.Event
- 3.5 ReportFragment的創建
- 3.6 LifecycleCallbacks.registerIn(activity)
- 3.7 ReportFragment.dispatch 版本兼容
- 3.8 Lifecycle.State
- 3.9 handleLifecycleEvent
- 3.10 sync
- 3.11 forwardPass
- 3.12 發送生命周期狀態
- 3.13 簡易流程圖
1.Lifecycle了解
- 到官方檔案下看 Google Lifecycle,Lifecycle的作用是:生命周期感知型組件可執行操作來回應另一個組件(如 Activity 和 Fragment)的生命周期狀態的變化,這些組件有助于您寫出更有條理且往往更精簡的代碼,這樣的代碼更易于維護,
- 我們之前開發,因為Activity 或者是 Fragment 的生命周期問題而間接引起的記憶體問題挺多的,比如每次都要寫資源,或者控制元件工具的回收釋放,如果忘記寫了,那么可能會引起記憶體泄漏,而現在搭配 Lifecycle,給我們生命周期的回呼,就不必再像以前在某個生命周期加上邏輯代碼,而是直接提前寫對應的代碼,更好解決生命周期問題,
2.生命周期獲取對比
2.1 之前的生命周期獲取
- 我們需要Activity重寫每一個生命周期的方法,在里面加入邏輯,如果某個回收忘記寫了,就可能觸發記憶體泄漏問題,
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")
}

2.2 Lifecycle回呼生命周期
- 使用Lifecycle,只要拿到Activity的Lifecycle,注冊觀察,就能回呼生命周期了,非常方便,如果寫的自定義View或者工具,需要生命周期感知,就可以利用Lifecycle,將邏輯寫在內部,代碼也更間接,使用者也不要去注意創建回收問題,
lifecycle.addObserver(object : LifecycleEventObserver {
override fun onStateChanged(source: LifecycleOwner, event: Lifecycle.Event) {
Log.d(TAG,event.toString())
}
})

3.原始碼分析
3.1 類關系圖

- 在Activity 獲取 Lifecycle,實際上是通過Activity的父類 ComponentActvitiy 獲取,父類實作了 LifecycleOwner 介面,就能獲取 Lifecycle ,最后注冊 LifecycleObserver 就能拿到生命周期回呼了,
3.2 ComponentActvitiy.onCreate
- 在ComponentActvitiy的 onCreate 方法里面可以看到 ReportFragment 的創建,
/* ComponentActvitiy */
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
...
ReportFragment.injectIfNeededIn(this);
...
}
3.3 getLifecycle方法
/* ComponentActvitiy */
private final LifecycleRegistry mLifecycleRegistry = new LifecycleRegistry(this);
@NonNull
@Override
public Lifecycle getLifecycle() {
return mLifecycleRegistry;
}
3.4 Lifecycle.Event
- Lifecycle.Event 是個列舉類,這里的生命周期 Event 并不是Fragment的,在后面的生命周期處理時會用上的,
public enum Event {
ON_CREATE,
ON_START,
ON_RESUME,
ON_PAUSE,
ON_STOP,
ON_DESTROY,
ON_ANY;
...
}
3.5 ReportFragment的創建
- ReportFragment 是一個 沒有界面的Fragment,如果有了解過Glide原理的同學,應該也知道這個方法,就是通過看不見的Fragment,來感知生命周期,讓使用者無需考慮生命周期的問題,
- 在SDK29以上的版本 使用的是 LifecycleCallbacks.registerIn(activity),
/* ReportFragment */
public static void injectIfNeededIn(Activity activity) {
if (Build.VERSION.SDK_INT >= 29) {
// On API 29+, we can register for the correct Lifecycle callbacks directly
LifecycleCallbacks.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 events
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();
}
}
3.6 LifecycleCallbacks.registerIn(activity)
- LifecycleCallbacks 實作了 Application.ActivityLifecycleCallbacks介面,在SDK29以上的生命周期分發是由Application 分發的,activity注冊就能回呼,
- 大名鼎鼎的LeakCanary在監聽Activity生命周期,也是使用 Application.ActivityLifecycleCallbacks,
@RequiresApi(29)
static class LifecycleCallbacks implements Application.ActivityLifecycleCallbacks {
static void registerIn(Activity activity) {
activity.registerActivityLifecycleCallbacks(new LifecycleCallbacks());
}
...
@Override
public void onActivityPostCreated(@NonNull Activity activity,
@Nullable Bundle savedInstanceState) {
dispatch(activity, Lifecycle.Event.ON_CREATE);
}
...
}
3.7 ReportFragment.dispatch 版本兼容
- 如果SDK版本小于29,ReportFragment的各個生命周期方法里,會呼叫 dispatch 方法,
- 比如 onActivityCreated,
- 反正無論是使用 LifecycleCallbacks.registerIn(activity),還是 Fragment 的生命周期回呼,最后都會dispatch,
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
dispatchCreate(mProcessListener);
dispatch(Lifecycle.Event.ON_CREATE);
}
private void dispatch(@NonNull Lifecycle.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.injectIfNeededIn
dispatch(getActivity(), event);
}
}
static void dispatch(@NonNull Activity activity, @NonNull Lifecycle.Event event) {
if (activity instanceof LifecycleRegistryOwner) {
((LifecycleRegistryOwner) activity).getLifecycle().handleLifecycleEvent(event);
return;
}
if (activity instanceof LifecycleOwner) {
Lifecycle lifecycle = ((LifecycleOwner) activity).getLifecycle();
if (lifecycle instanceof LifecycleRegistry) {
((LifecycleRegistry) lifecycle).handleLifecycleEvent(event);
}
}
}
3.8 Lifecycle.State
- 這個類跟Lifecycle.Event的關系看圖就能理解,
- State只有5個但是生命周期可是不止5個,所以Google他們設計時,就創建流程正著走,銷毀流程就反正走,

/* Lifecycle.State */
public enum State {
DESTROYED,
INITIALIZED,
CREATED,
STARTED,
RESUMED;
public boolean isAtLeast(@NonNull State state) {
return compareTo(state) >= 0;
}
}
3.9 handleLifecycleEvent
- LifecycleRegistryOwner 也是繼承 LifecycleOwner,所以他們最后都會執行 LifecycleRegistry 的 handleLifecycleEvent 方法,
- 就是把 Lifecycle.Event處理一下,轉化成 Lifecycle.State,
/* Lifecycle.Event */
@NonNull
public State getTargetState() {
switch (this) {
case ON_CREATE:
case ON_STOP:
return State.CREATED;
case ON_START:
case ON_PAUSE:
return State.STARTED;
case ON_RESUME:
return State.RESUMED;
case ON_DESTROY:
return State.DESTROYED;
case ON_ANY:
break;
}
throw new IllegalArgumentException(this + " has no target state");
}
- 將 Lifecycle.State 繼續往下傳,先用 mState 保存,再 sync 方法處理,
/* LifecycleRegistry */
public void handleLifecycleEvent(@NonNull Lifecycle.Event event) {
enforceMainThreadIfNeeded("handleLifecycleEvent");
moveToState(event.getTargetState());
}
private void moveToState(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 */
private void sync() {
//這是弱參考包裝過的LifecycleOwner
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.");
}
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;
}
3.11 forwardPass
- 反向的邏輯差不多,只是執行 backwardPass ,先轉換Stata,最后執行 observer.dispatchEvent,
- 這里又把 Lifecycle.State 轉回 Lifecycle.Event,然后給觀察者分發出去,
/* Lifecycle.Event */
@Nullable
public static Event upFrom(@NonNull State state) {
switch (state) {
case INITIALIZED:
return ON_CREATE;
case CREATED:
return ON_START;
case STARTED:
return ON_RESUME;
default:
return null;
}
}
- 轉換 Event.upFrom ,發送 observer.dispatchEvent,
/* LifecycleRegistry */
private void forwardPass(LifecycleOwner lifecycleOwner) {
Iterator<Map.Entry<LifecycleObserver, ObserverWithState>> ascendingIterator =
mObserverMap.iteratorWithAdditions();
while (ascendingIterator.hasNext() && !mNewEventOccurred) {
Map.Entry<LifecycleObserver, ObserverWithState> entry = ascendingIterator.next();
ObserverWithState observer = entry.getValue();
while ((observer.mState.compareTo(mState) < 0 && !mNewEventOccurred
&& mObserverMap.contains(entry.getKey()))) {
pushParentState(observer.mState);
//轉化
final Event event = Event.upFrom(observer.mState);
if (event == null) {
throw new IllegalStateException("no event up from " + observer.mState);
}
//發送
observer.dispatchEvent(lifecycleOwner, event);
popParentState();
}
}
}
3.12 發送生命周期狀態
- ObserverWithState 發送出 Lifecycle.Event ,至此就結束了,有注冊訂閱關系的地方就能收到,
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 = event.getTargetState();
mState = min(mState, newState);
mLifecycleObserver.onStateChanged(owner, event);
mState = newState;
}
}
3.13 簡易流程圖

轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/286349.html
標籤:其他
