參考:
https://developer.android.google.cn/topic/libraries/architecture/lifecycle?hl=zh-cn#java
https://developer.android.google.cn/reference/androidx/lifecycle/Lifecycle
文章目錄
- 1、概述
- 2、LifeCycle類
- 3、LifecycleOwner類
- 4、LifecycleObserver類
1、概述
Android Lifecycle 是一種用于管理 Android 組件(如 Activity 和 Fragment)生命周期的架構組件。Lifecycle 提供了一種在組件生命周期變化時觸發相應操作的方式,以幫助開發者編寫更加健壯和可維護的代碼。
Android 組件的生命周期包括多個階段,如創建(Create)、啟動(Start)、恢復(Resume)、暫停(Pause)、停止(Stop)和銷毀(Destroy)。在每個階段,組件可以執行特定的操作,如初始化界面、加載數據、保存狀態等。例如,經典的Activity組件的生命周期圖:
使用 Lifecycle 可以將與組件生命周期相關的操作集中到一個地方,并確保這些操作在正確的時機被調用。說白了,就是將生命周期的管理和業務實現分離,抽象成通用的公共組件,以實現代碼復用和抽象。
在 Android 框架中定義的大多數應用組件都存在生命周期。生命周期由操作系統或進程中運行的框架代碼管理。它們是 Android 工作原理的核心,應用必須遵循它們。如果不這樣做,可能會引發內存泄漏甚至應用崩潰。
Lifecycle 提供了以下主要的元素和功能:
- LifecycleOwner: 一個實現了 LifecycleOwner 接口的對象,通常是 Activity 或 Fragment。它負責提供生命周期的狀態。
- Lifecycle : 表示一個組件的生命周期狀態,如 CREATED、STARTED、RESUMED 等。可以通過 Lifecycle 對象來觀察和監聽生命周期狀態的變化。
- LifecycleObserver: 一個實現了 LifecycleObserver 接口的類,用于觀察和響應生命周期事件。
通過使用 Lifecycle,開發者可以避免常見的生命周期相關問題,如內存泄漏、UI 更新異常、數據不一致等。它提供了一種結構化的方式來管理生命周期,并使代碼更易于理解、測試和維護。
總之,Android Lifecycle 是一種用于管理 Android 組件生命周期的架構組件,它提供了一套機制和工具來觀察、響應和管理組件的狀態變化,使開發者能夠編寫更加可靠和健壯的代碼。
2、LifeCycle類
Lifecycle 是一個類,用于存儲有關組件(如 activity 或 fragment)的生命周期狀態的信息,并允許其他對象觀測此狀態。
Lifecycle 使用兩種主要枚舉跟蹤其關聯組件的生命周期狀態:
事件
從框架和 Lifecycle 類分派的生命周期事件。這些事件映射到 activity 和 fragment 中的回調事件。
狀態
Lifecycle 對象所跟蹤的組件的當前狀態。
跟蹤生命周期的流程如下:
熟悉狀態機的同學很容易理解,狀態在發生某些事情時就會躍遷到另一個狀態,上圖的箭頭就描述了某些事件發生時狀態的躍遷。
LifeCycle定義了以下幾種狀態:
public enum State {/*** Destroyed state for a LifecycleOwner. After this event, this Lifecycle will not dispatch* any more events. For instance, for an {@link android.app.Activity}, this state is reached* <b>right before</b> Activity's {@link android.app.Activity#onDestroy() onDestroy} call.*/DESTROYED,/*** Initialized state for a LifecycleOwner. For an {@link android.app.Activity}, this is* the state when it is constructed but has not received* {@link android.app.Activity#onCreate(android.os.Bundle) onCreate} yet.*/INITIALIZED,/*** Created state for a LifecycleOwner. For an {@link android.app.Activity}, this state* is reached in two cases:* <ul>* <li>after {@link android.app.Activity#onCreate(android.os.Bundle) onCreate} call;* <li><b>right before</b> {@link android.app.Activity#onStop() onStop} call.* </ul>*/CREATED,/*** Started state for a LifecycleOwner. For an {@link android.app.Activity}, this state* is reached in two cases:* <ul>* <li>after {@link android.app.Activity#onStart() onStart} call;* <li><b>right before</b> {@link android.app.Activity#onPause() onPause} call.* </ul>*/STARTED,/*** Resumed state for a LifecycleOwner. For an {@link android.app.Activity}, this state* is reached after {@link android.app.Activity#onResume() onResume} is called.*/RESUMED;/*** Compares if this State is greater or equal to the given {@code state}.** @param state State to compare with* @return true if this State is greater or equal to the given {@code state}*/public boolean isAtLeast(@NonNull State state) {return compareTo(state) >= 0;}}
定義的事件如下:
public enum Event {/*** Constant for onCreate event of the {@link LifecycleOwner}.*/ON_CREATE,/*** Constant for onStart event of the {@link LifecycleOwner}.*/ON_START,/*** Constant for onResume event of the {@link LifecycleOwner}.*/ON_RESUME,/*** Constant for onPause event of the {@link LifecycleOwner}.*/ON_PAUSE,/*** Constant for onStop event of the {@link LifecycleOwner}.*/ON_STOP,/*** Constant for onDestroy event of the {@link LifecycleOwner}.*/ON_DESTROY,/*** An {@link Event Event} constant that can be used to match all events.*/ON_ANY;
LifeCycle除了提供了生命周期的記錄,還提供了觀測的方法,采用了設計模式觀察者模式,
/*** Adds a LifecycleObserver that will be notified when the LifecycleOwner changes* state.* <p>* The given observer will be brought to the current state of the LifecycleOwner.* For example, if the LifecycleOwner is in {@link State#STARTED} state, the given observer* will receive {@link Event#ON_CREATE}, {@link Event#ON_START} events.** @param observer The observer to notify.*/@MainThreadpublic abstract void addObserver(@NonNull LifecycleObserver observer);/*** Removes the given observer from the observers list.* <p>* If this method is called while a state change is being dispatched,* <ul>* <li>If the given observer has not yet received that event, it will not receive it.* <li>If the given observer has more than 1 method that observes the currently dispatched* event and at least one of them received the event, all of them will receive the event and* the removal will happen afterwards.* </ul>** @param observer The observer to be removed.*/@MainThreadpublic abstract void removeObserver(@NonNull LifecycleObserver observer);
想要觀測該狀態,需要被Lifecycle添加為觀察者,當然也可以移除解除通知。
同時提供了一個供外部查詢當前狀態的接口:
/*** Returns the current state of the Lifecycle.** @return The current state of the Lifecycle.*/@MainThread@NonNullpublic abstract State getCurrentState();
3、LifecycleOwner類
LifecycleOwner只是個簡單的接口類,定義了一個獲取Lifecycle的方法。
public interface LifecycleOwner {/*** Returns the Lifecycle of the provider.** @return The lifecycle of the provider.*/@NonNullLifecycle getLifecycle();
}
想要擁有生命周期管理的組件只要實現該接口即可。
像ComponentActivity就繼承于該接口。
4、LifecycleObserver類
Lifecycle是一個被觀測對象,自然要有觀察者,即關心生命周期變化的人。提供了LifecycleObserver 類用于觀測Lifecycle,學java的都知道,java就喜歡極度抽象,LifecycleObserver 是個空接口類,啥都沒有。
public interface LifecycleObserver {}
觀察者的接口自然是觀測Lifecyle狀態變化,onXXX習慣用于表達XXX事件發生時的回調。
表達事件/狀態變化可以有兩種表達方式,一種是窮舉出所有的事件,一種是通過形參表達,android兩種形式都提供了:
FullLifecycleObserver 窮舉定義了所有事件回調:
interface FullLifecycleObserver extends LifecycleObserver {void onCreate(LifecycleOwner owner);void onStart(LifecycleOwner owner);void onResume(LifecycleOwner owner);void onPause(LifecycleOwner owner);void onStop(LifecycleOwner owner);void onDestroy(LifecycleOwner owner);
}
通過函數形參區分不同事件的接口定義LifecycleEventObserver :
/*** Class that can receive any lifecycle change and dispatch it to the receiver.* <p>* If a class implements both this interface and* {@link androidx.lifecycle.DefaultLifecycleObserver}, then* methods of {@code DefaultLifecycleObserver} will be called first, and then followed by the call* of {@link LifecycleEventObserver#onStateChanged(LifecycleOwner, Lifecycle.Event)}* <p>* If a class implements this interface and in the same time uses {@link OnLifecycleEvent}, then* annotations will be ignored.*/
public interface LifecycleEventObserver extends LifecycleObserver {/*** Called when a state transition event happens.** @param source The source of the event* @param event The event*/void onStateChanged(@NonNull LifecycleOwner source, @NonNull Lifecycle.Event event);
}
注釋里提到,如果一個Observer同時實現了這兩種形式的接口,FullLifecycleObserver的相應接口會先被調用,其次才是onStateChanged這個接口。
同時還定義了一個空實現的DefaultLifecycleObserver,這樣我們可以根據需要,override部分接口。
在最后,我們補全一張類圖: