Android Lifecycle的事件与状态映射关系

复制代码
ComponentActivity:
Kotlin 复制代码
open class ComponentActivity() :
...{
    override fun onCreate(savedInstanceState: Bundle?) {
        // Restore the Saved State first so that it is available to
        // OnContextAvailableListener instances
        savedStateRegistryController.performRestore(savedInstanceState)
        contextAwareHelper.dispatchOnContextAvailable(this)
        super.onCreate(savedInstanceState)
        //注入一个无UI的fragment监听activity的生命周期
        ReportFragment.injectIfNeededIn(this)
        if (contentLayoutId != 0) {
            setContentView(contentLayoutId)
        }
    }
}
复制代码
ReportFragment.injectIfNeededIn(this):
Kotlin 复制代码
public fun 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
            val manager = activity.fragmentManager
            //和glide框架一样
            if (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()
            }
        }
复制代码
ReportFragment:

分发事件

Kotlin 复制代码
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 activity
        processListener = null
    }

Lifecycle 事件和状态:

Kotlin 复制代码
public val targetState: State
            get() {
                when (this) {
                    ON_CREATE, ON_STOP -> return State.CREATED
                    ON_START, ON_PAUSE -> return State.STARTED
                    ON_RESUME -> return State.RESUMED
                    ON_DESTROY -> return State.DESTROYED
                    ON_ANY -> {}
                }
                throw IllegalArgumentException("$this has no target state")
            }

|-----------|---|---|---|-----------|
| 事件->状态 映射表 |||||
| Event || 触发方法 || 执行后状态 |
| |||||
| ON_CREATE | | onCreate() || CREATED |
| ON_START | | onStart() || STARTED |
| ON_RESUME | | onResume() || RESUMED |
| ON_PAUSE | | onPause() || STARTED |
| ON_STOP | | onStop() || CREATED |
| ON_DESTROY || onDestroy() || DESTROYED |
| ON_ANY | | 任何事件 || 保持当前状态 |

以上是通过ReportFragment的生命周期函数进行对应的事件分发获取对应的状态,比如

Kotlin 复制代码
override fun onActivityCreated(savedInstanceState: Bundle?) {
        super.onActivityCreated(savedInstanceState)
        dispatchCreate(processListener)
        dispatch(Lifecycle.Event.ON_START)
    }
复制代码
dispatch(Lifecycle.Event.ON_START)->dispatch(activity, event)->
复制代码
lifecycle.handleLifecycleEvent(event)->moveToState(event.targetState)
Kotlin 复制代码
private fun moveToState(next: State) {
        //如果当前状态state=targetState直接return
        if (state == next) {
            return
        }
        check(!(state == State.INITIALIZED && next == State.DESTROYED)) {
            "State must be at least CREATED to move to $next, but was $state in component " +
                "${lifecycleOwner.get()}"
        }
        state = next
        if (handlingEvent || addingObserverCounter != 0) {
            newEventOccurred = true
            // we will figure out what to do on upper level.
            return
        }
        handlingEvent = true
        //否则进行同步操作
        sync()
        handlingEvent = false
        if (state == State.DESTROYED) {
            observerMap = FastSafeIterableMap()
        }
    }

// 状态同步
private fun sync() {
        val lifecycleOwner = lifecycleOwner.get()
            ?: throw IllegalStateException(
                "LifecycleOwner of this LifecycleRegistry is already " +
                    "garbage collected. It is too late to change lifecycle state."
            )
        while (!isSynced) {
            newEventOccurred = false
            if (state < observerMap.eldest()!!.value.state) {
                // 状态后移
                backwardPass(lifecycleOwner)
            }
            val newest = observerMap.newest()
            if (!newEventOccurred && newest != null && state > newest.value.state) {
                // 状态前移
                forwardPass(lifecycleOwner)
            }
        }
        newEventOccurred = false
        _currentStateFlow.value = currentState
    }

// 假设状态前移
private fun forwardPass(lifecycleOwner: LifecycleOwner) {
        @Suppress()
        val ascendingIterator: Iterator<Map.Entry<LifecycleObserver, ObserverWithState>> =
            observerMap.iteratorWithAdditions()
        while (ascendingIterator.hasNext() && !newEventOccurred) {
            val (key, observer) = ascendingIterator.next()
            while (observer.state < state && !newEventOccurred && observerMap.contains(key)
            ) {
                pushParentState(observer.state)
                // 通过状态得出对应的事件
                val event = Event.upFrom(observer.state)
                    ?: throw IllegalStateException("no event up from ${observer.state}")
                observer.dispatchEvent(lifecycleOwner, event)
                popParentState()
            }
        }
    }

// 通过STARTED状态获取到ON_RESUME事件
public fun upFrom(state: State): Event? {
                return when (state) {
                    State.INITIALIZED -> ON_CREATE
                    State.CREATED -> ON_START
                    State.STARTED -> ON_RESUME
                    else -> null
                }
            }

// 之后执行observer.dispatchEvent(lifecycleOwner, event)
fun dispatchEvent(owner: LifecycleOwner?, event: Event) {
            val newState = event.targetState
            state = min(state, newState)
            // 得到ON_RESUME事件通过反射执行对应的生命周期方法
            lifecycleObserver.onStateChanged(owner!!, event)
            // Lifecycle获取最新的状态
            state = newState
        }

// 通过反射执行onResume()方法
class ReflectiveGenericLifecycleObserver implements LifecycleEventObserver {
    private final Object mWrapped;
    private final ClassesInfoCache.CallbackInfo mInfo;

    ReflectiveGenericLifecycleObserver(Object wrapped) {
        this.mWrapped = wrapped;
        this.mInfo = ClassesInfoCache.sInstance.getInfo(this.mWrapped.getClass());
    }

    public void onStateChanged(@NonNull LifecycleOwner source, @NonNull Lifecycle.Event event) {
        this.mInfo.invokeCallbacks(source, event, this.mWrapped);
    }
}

这样通过ReportFragment分发事件和对应状态的处理,Lifecycle就监听到activity的生命周期方法了

相关推荐
十六年开源服务商3 小时前
2026服务器配置优化与WordPress运维实战指南
android·运维·服务器
音视频牛哥5 小时前
大牛直播SDK(SmartMediaKit)Android平台Unity3D RTSP/RTMP播放器集成实践
android·unity3d·rtsp播放器·rtmp播放器·unity3d rtmp播放器·安卓unity rtsp播放器·安卓unity rtmp播放器
w1wi5 小时前
安卓抓包完全指南(一):从入门到 SSL Pinning 绕过
android·网络协议·ssl
aqi007 小时前
一文理清 HarmonyOS 6.0.2 涵盖的十个升级点
android·华为·harmonyos·鸿蒙·harmony
赏金术士7 小时前
Jetpack Compose 状态提升(State Hoisting)完全指南
android·kotlin·compose
BoomHe8 小时前
git Rebase 为任意一笔提交补上 Change-Id
android·git·android studio
TDengine (老段)8 小时前
TDengine 超级表/子表/普通表 — 设计理念与内部表示
android·大数据·数据库·物联网·时序数据库·tdengine·涛思数据
shuaiqinke9 小时前
【分享】Edge浏览器|内置扩展仓库|支持油猴|上网无限制
android·前端·人工智能·edge
Hali_Botebie9 小时前
岭回归(Ridge Regression),也称为L2正则化回归
数据挖掘·回归·kotlin