導包
[versions]
lifecycle_version = "2.3.1"[libraries]
androidx-viewmodel = { group = "androidx.lifecycle", name = "lifecycle-viewmodel-ktx", version.ref = "lifecycle_version" }
androidx-livedata = { group = "androidx.lifecycle", name = "lifecycle-livedata-ktx", version.ref = "lifecycle_version" }
androidx-runtime = { group = "androidx.lifecycle", name = "lifecycle-runtime-ktx", version.ref = "lifecycle_version" }
androidx-viewmodel-savestate = { group = "androidx.lifecycle", name = "lifecycle-viewmodel-savedstate", version.ref = "lifecycle_version" }
androidx-lifecycle-compiler = { group = "androidx.lifecycle", name = "lifecycle-compiler", version.ref = "lifecycle_version" }
androidx-lifecycle-service = { group = "androidx.lifecycle", name = "lifecycle-service", version.ref = "lifecycle_version" } #service 中使用lifecycle
androidx-lifecycle-process = { group = "androidx.lifecycle", name = "lifecycle-process", version.ref = "lifecycle_version" } #application 中使用lifecycle
核心組件協作
?LifecycleOwner?:生命周期擁有者(如Activity/Fragment),通過getLifecycle()提供Lifecycle對象
?LifecycleRegistry?:Lifecycle的具體實現,負責狀態管理和事件分發
LifecycleObserver?:觀察者接口,業務組件通過實現它來接收生命周期事件
LifecycleObserver
LifecycleObserver是Android Jetpack架構組件中的關鍵接口,用于構建能夠感知Activity/Fragment生命周期的觀察者組件。它通過解耦生命周期管理邏輯與UI組件,幫助開發者編寫更有條理且易于維護的代碼
package androidx.lifecycle/*** Marks a class as a LifecycleObserver. Don't use this interface directly. Instead implement either* [DefaultLifecycleObserver] or [LifecycleEventObserver] to be notified about* lifecycle events.
翻譯如下
將一個類標記為生命周期觀察者。不要直接使用此接口。相反,實現DefaultLifecycleObserver或LifecycleEventObserver,以接收生命周期事件的通知。** @see Lifecycle Lifecycle - for samples and usage patterns.*/
public interface LifecycleObserver
so 我們
class MyLifecycleObserver:LifecycleEventObserver {override fun onStateChanged(source: LifecycleOwner, event: Lifecycle.Event) {Log.i("zq_demo","event>>${event.name} ${event.targetState}")}
}
然后我們activity中 添加如下代碼
lifecycle.addObserver(MyLifecycleObserver())
結果
app退到后臺
app回前臺
app 退出
發現木有
event>>ON_PAUSE STARTED ON_PAUSE時是STARTED
event>>ON_STOP CREATED ON_STOP時是CREATED
why???
public abstract class Lifecycle {
//省略public enum class Event {/*** Constant for onCreate event of the [LifecycleOwner].*/ON_CREATE,/*** Constant for onStart event of the [LifecycleOwner].*/ON_START,/*** Constant for onResume event of the [LifecycleOwner].*/ON_RESUME,/*** Constant for onPause event of the [LifecycleOwner].*/ON_PAUSE,/*** Constant for onStop event of the [LifecycleOwner].*/ON_STOP,/*** Constant for onDestroy event of the [LifecycleOwner].*/ON_DESTROY,/*** An [Event] constant that can be used to match all events.*/ON_ANY;public val targetState: Stateget() {when (this) {ON_CREATE, ON_STOP -> return State.CREATED //看這里看這里ON_START, ON_PAUSE -> return State.STARTED //看這里看這里ON_RESUME -> return State.RESUMEDON_DESTROY -> return State.DESTROYEDON_ANY -> {}}throw IllegalArgumentException("$this has no target state")}
}
}
為什么要這么搞呢?
下面是deepseek的回答
Android生命周期中ON_PAUSE事件對應STARTED狀態的原因
Android生命周期設計中,Lifecycle.Event.ON_PAUSE對應Lifecycle.State.STARTED狀態,這種設計基于Activity生命周期的狀態轉換邏輯和實際應用場景考慮。
生命周期狀態與事件的基本關系
Android生命周期定義了5種狀態和7種事件:
- 5種狀態?:INITIALIZED、CREATED、STARTED、RESUMED、DESTROYED
- 7種事件?:ON_CREATE、ON_START、ON_RESUME、ON_PAUSE、ON_STOP、ON_DESTROY、ON_ANY
其中STARTED狀態表示Activity已可見但未獲得焦點,而ON_PAUSE事件表示Activity正在停止但仍可見?
ON_PAUSE與STARTED對應的技術原因
1? 狀態定義一致性?:當Activity觸發ON_PAUSE時,它仍然可見(如被透明Activity或對話框部分遮擋),這符合STARTED狀態"已可見但未獲得焦點"的定義?34。
?2 狀態轉換順序?:Android使用狀態機模型管理生命周期,確保狀態轉換有序。從RESUMED狀態出發,觸發ON_PAUSE后應進入STARTED狀態,而非直接跳轉到CREATED或STOPPED?15。
3? 用戶體驗考慮?:這種設計允許Activity在被部分遮擋時仍能保持可見狀態,同時釋放焦點資源給新Activity,實現平滑過渡?26。
?4 資源管理優化?:ON_PAUSE對應STARTED狀態的設計確保了系統可以在Activity失去焦點但仍可見時進行合理的資源分配,而不是立即停止所有功能?
實際場景示例
當用戶打開一個對話框或透明Activity時:
原Activity觸發ON_PAUSE事件
狀態變為STARTED(可見但無焦點)
如果用戶返回,會觸發ON_RESUME回到RESUMED狀態
如果被完全覆蓋,才會觸發ON_STOP進入CREATED狀態?。
這種設計使Android能夠精細控制Activity的可見性和交互狀態,為開發者提供明確的生命周期回調時機進行資源管理?。
LifecycleOwner
看 繼承或實現關系
- MainActivity : AppCompatActivity()
- AppCompatActivity extends FragmentActivity
- FragmentActivity extends ComponentActivity
- public class ComponentActivity extends androidx.core.app.ComponentActivity implements LifecycleOwner
不光activity 實現了 LifecycleOwner ; Fragment 也實現了
LifecycleOwner是Android Jetpack架構組件中的核心接口,用于表示具有Android生命周期的組件。根據官方文檔,LifecycleOwner的主要作用是?抽象生命周期所有權?,使自定義組件能夠感知宿主(如Activity/Fragment)的生命周期變化,而無需在宿主中直接實現相關代碼?
- ?生命周期提供者?:通過getLifecycle()方法提供Lifecycle對象,作為生命周期狀態和事件的橋梁?
- 觀察者模式實現?:與LifecycleObserver配合使用,形成觀察者模式架構?
- 狀態管理?:維護5種生命周期狀態(INITIALIZED、CREATED、STARTED、RESUMED、DESTROYED)和7種事件(ON_CREATE等)?
上邊我們添加lifecycyleObserver時使用
lifecycle.addObserver(MyLifecycleObserver())
看這個lifecycle
public class ComponentActivity ...{
....private final LifecycleRegistry mLifecycleRegistry = new LifecycleRegistry(this);
....@NonNull@Overridepublic Lifecycle getLifecycle() {return mLifecycleRegistry;}
....
}
open class LifecycleRegistry private constructor(provider: LifecycleOwner,private val enforceMainThread: Boolean
) : Lifecycle() {
LifecycleOwner的實現類可多 ProcessLifecycleOwner 用于監聽應用進程生命周期的變化
我們比貓畫虎
于是乎:
class MyLifecyclerOwner:LifecycleOwner {private val registry = LifecycleRegistry(this)fun onCreate(){registry.currentState = Lifecycle.State.CREATED}fun onStart(){registry.currentState = Lifecycle.State.STARTED}fun onResume(){registry.currentState = Lifecycle.State.RESUMED}fun onPause(){registry.currentState = Lifecycle.State.STARTED}fun onStop(){registry.currentState = Lifecycle.State.CREATED}fun onDestroy(){registry.currentState = Lifecycle.State.DESTROYED}override val lifecycle: Lifecycleget() = registry
}
使用
class MainActivity : AppCompatActivity() {val owner = MyLifecyclerOwner()override fun onCreate(savedInstanceState: Bundle?) {super.onCreate(savedInstanceState)enableEdgeToEdge()setContentView(R.layout.activity_main)// lifecycle.addObserver(MyLifecycleObserver())owner.onCreate()owner.lifecycle.addObserver(MyLifecycleObserver())Log.i("zq_demo","onCreate")}override fun onStart() {super.onStart()owner.onStart()Log.i("zq_demo","onStart")}override fun onResume() {super.onResume()owner.onResume()Log.i("zq_demo","onResume")}override fun onPause() {super.onPause()owner.onPause()Log.i("zq_demo","onPause")}override fun onStop() {super.onStop()owner.onStop()Log.i("zq_demo","onStop")}override fun onDestroy() {super.onDestroy()owner.onDestroy()Log.i("zq_demo","onDestroy")}}
運行結果
與上邊一樣一樣滴;
LifecycleRegistry 以下為deepseek 說明
LifecycleRegistry是Android Jetpack架構組件中Lifecycle接口的核心實現類,負責管理Android組件(Activity/Fragment)的生命周期狀態并分發給觀察者。作為生命周期管理的中樞系統,它實現了以下核心功能:
- 1 狀態管理?:維護5種生命周期狀態(INITIALIZED→CREATED→STARTED→RESUMED→DESTROYED)和7種事件(ON_CREATE等)?
- 2 觀察者模式實現?:通過addObserver()/removeObserver()管理觀察者列表,實現生命周期事件的訂閱-發布機制?
- 3 事件分發?:當宿主狀態變化時,同步狀態并通知所有注冊的觀察者?
- 4 線程安全保證?:確保生命周期事件在主線程分發,狀態變更操作線程安全?
內部實現與狀態機模型
狀態機設計原理
LifecycleRegistry采用?有限狀態機(FSM)?模型管理生命周期,狀態轉換規則嚴格遵循Android生命周期邏輯:
// 狀態轉換規則示例
static State getStateAfter(Event event) {switch(event) {case ON_CREATE: case ON_STOP: return CREATED;case ON_START: case ON_PAUSE: return STARTED;case ON_RESUME: return RESUMED;case ON_DESTROY: return DESTROYED;}throw new IllegalArgumentException("Unexpected event");
}
狀態轉換路徑:
DESTROYED ← ON_DESTROY ← CREATED ← ON_STOP ← STARTED ← ON_PAUSE ← RESUMED
ON_CREATE → ON_START → ON_RESUME →
關鍵實現機制
- 1 雙向同步算法?:通過sync()方法確保觀察者狀態與宿主狀態一致:
private void sync() {while (!isSynced()) {// 向后回退狀態 (RESUMED → STARTED → CREATED)if (mState < eldestObserverState) backwardPass();// 向前推進狀態 (CREATED → STARTED → RESUMED)if (mState > newestObserverState) forwardPass();}
}
- 2 觀察者包裝機制?:通過Lifecycling類將觀察者統一包裝為LifecycleEventObserver,支持接口回調和注解兩種方式?
- 3 狀態驗證?:提供currentState.isAtLeast()方法驗證狀態條件?
與LifecycleOwner的協作關系
協作流程
- 1 宿主綁定?:Activity/Fragment實現LifecycleOwner接口,通過getLifecycle()返回LifecycleRegistry實例?
- 2 事件捕獲?:
- Fragment:直接通過生命周期回調觸發handleLifecycleEvent()
- Activity:通過ReportFragment代理捕獲事件?
- 3 觀察者注冊?:業務組件調用getLifecycle().addObserver()注冊監聽
自定義LifecycleOwner實現
非Activity/Fragment類可通過實現LifecycleOwner接口創建自定義生命周期宿主:
class CustomOwner : LifecycleOwner {private val registry = LifecycleRegistry(this)override fun getLifecycle(): Lifecycle = registryfun updateState(newState: Lifecycle.State) {registry.currentState = newState}
}
事件分發機制詳解
分發流程
- 1 事件觸發?:Activity/Fragment生命周期變化時,ReportFragment調用dispatch(Lifecycle.Event)?
- 2 事件處理?:LifecycleRegistry.handleLifecycleEvent()根據事件類型計算新狀態?
- 3 狀態同步?:通過sync()方法同步所有觀察者狀態?
- 4 觀察者通知?:調用觀察者的onStateChanged()方法或對應注解方法?
線程模型特性
- 主線程限制?:所有生命周期回調強制在主線程執行?
- 線程安全保證?:狀態變更操作通過同步塊保證原子性?
- 異步處理建議?:耗時操作應切換到工作線程執行?
實際應用場景與最佳實踐
典型使用場景
- 1 資源生命周期管理?:
- 在ON_START時連接服務,ON_STOP時自動釋放?
- 網絡請求在頁面不可見時自動取消?
- 2 組件解耦?:
class LocationObserver : DefaultLifecycleObserver {override fun onStart(owner: LifecycleOwner) {startLocationUpdates()}override fun onStop(owner: LifecycleOwner) {stopLocationUpdates()}
}
- 3 自定義生命周期宿主?:為非UI組件(如Service、自定義View)添加生命周期感知能力?
最佳實踐指南
-
1 觀察者注冊方式選擇?:
- 推薦使用DefaultLifecycleObserver接口(優于已廢棄的注解方式)?
- 避免在DESTROYED狀態后注冊觀察者?
-
2 資源管理規范?:
- 在配對回調中執行相反操作(如start/stop)?
- 使用isAtLeast()驗證狀態條件?
-
3 性能優化?:
- 及時移除不再需要的觀察者?
- 避免在回調中執行耗時操作?
Lifecycle
Lifecycle是Android Jetpack架構組件中的基礎接口,定義了Android組件生命周期管理的標準化模型。作為生命周期感知組件的核心,它通過狀態和事件的抽象,實現了對Activity/Fragment等組件生命周期的統一管理?
關鍵方法說明
?- addObserver()?:注冊生命周期觀察者,開始接收生命周期事件?
?- removeObserver()?:移除已注冊的觀察者,停止事件接收?
?- getCurrentState()?:獲取當前生命周期狀態?
?- handleLifecycleEvent()?:處理生命周期事件并觸發狀態轉換(由LifecycleRegistry實現)?
public class ComponentActivity@Overrideprotected void onCreate(@Nullable Bundle savedInstanceState) {// Restore the Saved State first so that it is available to// OnContextAvailableListener instancesmSavedStateRegistryController.performRestore(savedInstanceState);mContextAwareHelper.dispatchOnContextAvailable(this);super.onCreate(savedInstanceState);ReportFragment.injectIfNeededIn(this); //注意這一句if (mContentLayoutId != 0) {setContentView(mContentLayoutId);}}}
查看ReportFragment
open class ReportFragment() : android.app.Fragment() {
...override fun onActivityCreated(savedInstanceState: Bundle?) {super.onActivityCreated(savedInstanceState)dispatchCreate(processListener)dispatch(Lifecycle.Event.ON_CREATE)}override fun onStart() {super.onStart()dispatchStart(processListener)dispatch(Lifecycle.Event.ON_START)}override fun onResume() {super.onResume()dispatchResume(processListener)dispatch(Lifecycle.Event.ON_RESUME)}override fun onPause() {super.onPause()dispatch(Lifecycle.Event.ON_PAUSE)}override fun onStop() {super.onStop()dispatch(Lifecycle.Event.ON_STOP)}override fun onDestroy() {super.onDestroy()dispatch(Lifecycle.Event.ON_DESTROY)// just want to be sure that we won't leak reference to an activityprocessListener = null}private fun dispatch(event: Lifecycle.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.injectIfNeededIndispatch(activity, event)}}
...companion object {private const val REPORT_FRAGMENT_TAG ="androidx.lifecycle.LifecycleDispatcher.report_fragment_tag"@JvmStaticfun injectIfNeededIn(activity: Activity) {if (Build.VERSION.SDK_INT >= 29) {// On API 29+, we can register for the correct Lifecycle callbacks directlyLifecycleCallbacks.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 eventsval manager = activity.fragmentManagerif (manager.findFragmentByTag(REPORT_FRAGMENT_TAG) == null) {manager.beginTransaction().add(ReportFragment(), REPORT_FRAGMENT_TAG).commit()// Hopefully, we are the first to make a transaction.manager.executePendingTransactions()}}@JvmStaticinternal fun dispatch(activity: Activity, event: Lifecycle.Event) {if (activity is LifecycleRegistryOwner) {activity.lifecycle.handleLifecycleEvent(event)return}if (activity is LifecycleOwner) {val lifecycle = (activity as LifecycleOwner).lifecycleif (lifecycle is LifecycleRegistry) {lifecycle.handleLifecycleEvent(event)}}}@JvmStatic@get:JvmName("get")val Activity.reportFragment: ReportFragmentget() {return this.fragmentManager.findFragmentByTag(REPORT_FRAGMENT_TAG) as ReportFragment}}
}
代碼的邏輯很清晰,主要通過一個透明的Fragment來分發生命周期事件,這樣對于Activity來說是無侵入的
最終調用到了
@JvmStaticinternal fun dispatch(activity: Activity, event: Lifecycle.Event) {if (activity is LifecycleRegistryOwner) {activity.lifecycle.handleLifecycleEvent(event)return}if (activity is LifecycleOwner) {val lifecycle = (activity as LifecycleOwner).lifecycleif (lifecycle is LifecycleRegistry) {lifecycle.handleLifecycleEvent(event)}}}
也就是上面 lifecycle(LifecycleRegistry).handleLifecycleEvent(event)
open fun handleLifecycleEvent(event: Event) {enforceMainThreadIfNeeded("handleLifecycleEvent")moveToState(event.targetState)}private fun moveToState(next: State) {if (state == next) {return}check(!(state == State.INITIALIZED && next == State.DESTROYED)) {"no event down from $state in component ${lifecycleOwner.get()}"}state = nextif (handlingEvent || addingObserverCounter != 0) {newEventOccurred = true// we will figure out what to do on upper level.return}handlingEvent = truesync()handlingEvent = falseif (state == State.DESTROYED) {observerMap = FastSafeIterableMap()}}
后邊代碼就不沾了 可以自己點點點 也可以參考 點這里點這里