应用生命周期
源:Android Lifecycle | iOS App Lifecycle
监听应用前后台切换、启动和退出等生命周期事件,是资源管理、数据同步的关键。本文展示如何跨平台监听应用生命周期。
平台差异对比
| 平台 | 原生 API | 生命周期回调 | 适用场景 |
|---|---|---|---|
| Android | ProcessLifecycleOwner | onCreate、onStart、onStop | 全局生命周期监听 |
| iOS | UIApplicationDelegate / SceneDelegate | didBecomeActive、didEnterBackground | 应用状态变化 |
| Desktop | - | - | 无标准生命周期 |
expect/actual 实现方案
标准代码块
kotlin
enum class AppState {
FOREGROUND,
BACKGROUND
}
interface AppLifecycleObserver {
fun onAppStateChanged(state: AppState)
}
expect object AppLifecycle {
fun addObserver(observer: AppLifecycleObserver)
fun removeObserver(observer: AppLifecycleObserver)
fun getCurrentState(): AppState
}kotlin
import androidx.lifecycle.DefaultLifecycleObserver
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.ProcessLifecycleOwner
actual object AppLifecycle {
private val observers = mutableSetOf<AppLifecycleObserver>()
private var currentState = AppState.FOREGROUND
private val lifecycleObserver = object : DefaultLifecycleObserver {
override fun onStart(owner: LifecycleOwner) {
currentState = AppState.FOREGROUND
observers.forEach { it.onAppStateChanged(AppState.FOREGROUND) }
}
override fun onStop(owner: LifecycleOwner) {
currentState = AppState.BACKGROUND
observers.forEach { it.onAppStateChanged(AppState.BACKGROUND) }
}
}
fun init() {
ProcessLifecycleOwner.get().lifecycle.addObserver(lifecycleObserver)
}
actual fun addObserver(observer: AppLifecycleObserver) {
observers.add(observer)
}
actual fun removeObserver(observer: AppLifecycleObserver) {
observers.remove(observer)
}
actual fun getCurrentState(): AppState {
return currentState
}
}kotlin
import platform.Foundation.NSNotificationCenter
import platform.UIKit.*
actual object AppLifecycle {
private val observers = mutableSetOf<AppLifecycleObserver>()
private var currentState = AppState.FOREGROUND
fun init() {
val center = NSNotificationCenter.defaultCenter
center.addObserverForName(
UIApplicationDidBecomeActiveNotification,
null,
null
) { _ ->
currentState = AppState.FOREGROUND
observers.forEach { it.onAppStateChanged(AppState.FOREGROUND) }
}
center.addObserverForName(
UIApplicationDidEnterBackgroundNotification,
null,
null
) { _ ->
currentState = AppState.BACKGROUND
observers.forEach { it.onAppStateChanged(AppState.BACKGROUND) }
}
}
actual fun addObserver(observer: AppLifecycleObserver) {
observers.add(observer)
}
actual fun removeObserver(observer: AppLifecycleObserver) {
observers.remove(observer)
}
actual fun getCurrentState(): AppState {
return currentState
}
}kotlin
actual object AppLifecycle {
actual fun addObserver(observer: AppLifecycleObserver) {}
actual fun removeObserver(observer: AppLifecycleObserver) {}
actual fun getCurrentState(): AppState = AppState.FOREGROUND
}依赖补充
Android Lifecycle
kotlin
kotlin {
sourceSets {
androidMain.dependencies {
implementation("androidx.lifecycle:lifecycle-process:2.7.0")
}
}
}