Androidx Lifecycle 源码阅读笔记

简单使用

Androidx 库中有很多地方都有用到 Lifecycle 去监听组件的生命周期,例如常见的 ActivityFragment 等等。简单的使用如下:

Kotlin 复制代码
class MainActivity : ComponentActivity() {

    val lifecycleObserver1: LifecycleObserver = object : DefaultLifecycleObserver {
        override fun onCreate(owner: LifecycleOwner) {
            // TODO: 
        }
    }
    
    val lifecycleObserver2: LifecycleObserver = object : LifecycleObserver {
        
        @OnLifecycleEvent(Lifecycle.Event.ON_CREATE)
        fun myOnCreate() {
            // TODO:
        }
    }
    
    init {
        lifecycle.addObserver(lifecycleObserver1)
    }
}

这里要说明的是上面的代码 lifecycleObserver2 是通过 @OnLifecycleEvent() 注解的方式去监听生命周期,看上去很酷炫,不过酷炫也是需要代价的,性能要差一丢丢,因为内部是用反射实现的。而且 @OnLifecycleEvent()注解已经弃用,推荐使用 DefaultLifecycleObserver

LifecycleRegistry 工作原理

其中上面的 ComponentActivity 是实现了 LifecycleOwner 接口的。其接口定义如下:

Kotlin 复制代码
public interface LifecycleOwner {
    /**
     * Returns the Lifecycle of the provider.
     *
     * @return The lifecycle of the provider.
     */
    public val lifecycle: Lifecycle
}

朴实无华,其实需要实现类提供一个 Lifecycle,也就是我们上面的 demo 代码中的 lifecycle

这里简单来描述一下我们常用的 Activity 的继承关系,androidx.fragment.app.FragmentActivity -> androidx.activity.ComponentActivity -> androidx.core.app.ComponentActivity -> Activity

没错,有两个 ComponentActivityActivityLifecycle 生命周期管理,就是由他们实现的。

我们先来看看 androidx.core.app.ComponentActivity 中的 lifecycle 的实现:

Kotlin 复制代码
// ...

@Suppress("LeakingThis")
private val lifecycleRegistry = LifecycleRegistry(this)

// ...

override val lifecycle: Lifecycle
    get() = lifecycleRegistry
// ...

这个 Lifecycle 真正的实现就是 LifecycleRegistry。这个 lifecycle 也是我们上面 demo 中使用的 lifecycle

我们先来看看 LifecycleRegistry#addObserver() 方法的实现:

Kotlin 复制代码
override fun addObserver(observer: LifecycleObserver) {
    // 检查是否需要验证主线程
    enforceMainThreadIfNeeded("addObserver")
    // observer 初始化的状态,要么 INITIALIZED,要么 DESTROYED.
    val initialState = if (state == State.DESTROYED) State.DESTROYED else State.INITIALIZED
    // 将 observer 用 ObserverWithState 类包裹,其中会记录 Observer 对应的状态
    val statefulObserver = ObserverWithState(observer, initialState)
    // 将 observer 添加到 observerMap 字典中。
    val previous = observerMap.putIfAbsent(observer, statefulObserver)
    if (previous != null) {
        // 如果已经添加过了,就直接返回
        return
    }
    val lifecycleOwner = lifecycleOwner.get()
        ?: // it is null we should be destroyed. Fallback quickly
        return
    // 是否有其他的线程在添加 observer 或者当前状态正在更新    
    val isReentrance = addingObserverCounter != 0 || handlingEvent
    // 计算当前 observer 需要更新到的目标状态
    var targetState = calculateTargetState(observer)
    // 正在添加的 observer 数量 + 1
    addingObserverCounter++
    // 更新当前的 observer 到目标状态
    while (statefulObserver.state < targetState && observerMap.contains(observer)
    ) {
        pushParentState(statefulObserver.state)
        // 获取对应状态的下一个状态的需要的更新事件
        val event = Event.upFrom(statefulObserver.state)
            ?: throw IllegalStateException("no event up from ${statefulObserver.state}")
            
        statefulObserver.dispatchEvent(lifecycleOwner, event)
        popParentState()
        // mState / subling may have been changed recalculate
        targetState = calculateTargetState(observer)
    }
    if (!isReentrance) {
        // we do sync only on the top level.
        // 再次同步状态到所有的 observer
        sync()
    }
    // 正在添加的 observer 数量 - 1
    addingObserverCounter--
}

假如当前你的 Activity 已经执行完毕了 onResume() 方法了,你添加的 Observer 就会依次回调 onCreate() -> onStart() -> onResume() 的生命周期,上面的大部份代码都是在做这个事情。

所有的 observer 都会被添加到 observerMap 成员变量中,他是一个自定义的 Map,它的实现类是 FastSafeIterableMap,他其中会用链表管理 Element,这有一个好处就是可以获取到 Observer 的添加顺序,因为它的状态下发至 Observer 会严格按照它的添加顺序处理,后面我们会看到这个代码。

这里还要说明一下 Lifecycle 中的状态和事件。很多人都理不清楚他们。这里举一个例子:假如 去吃饭 是一个事件,那么在 去吃饭 这个事件执行完毕后,你的状态就由 饿 -> 。我们来看看 Lifecycle 中的状态。

Kotlin 复制代码
/**
 * Lifecycle states. You can consider the states as the nodes in a graph and
 * [Event]s as the edges between these nodes.
 */
public enum class State {
    /**
     * Destroyed state for a LifecycleOwner. After this event, this Lifecycle will not dispatch
     * any more events. For instance, for an [android.app.Activity], this state is reached
     * **right before** Activity's [onDestroy][android.app.Activity.onDestroy] call.
     */
    DESTROYED,

    /**
     * Initialized state for a LifecycleOwner. For an [android.app.Activity], this is
     * the state when it is constructed but has not received
     * [onCreate][android.app.Activity.onCreate] yet.
     */
    INITIALIZED,

    /**
     * Created state for a LifecycleOwner. For an [android.app.Activity], this state
     * is reached in two cases:
     *
     *  * after [onCreate][android.app.Activity.onCreate] call;
     *  * **right before** [onStop][android.app.Activity.onStop] call.
     *
     */
    CREATED,

    /**
     * Started state for a LifecycleOwner. For an [android.app.Activity], this state
     * is reached in two cases:
     *
     *  * after [onStart][android.app.Activity.onStart] call;
     *  * **right before** [onPause][android.app.Activity.onPause] call.
     *
     */
    STARTED,

    /**
     * Resumed state for a LifecycleOwner. For an [android.app.Activity], this state
     * is reached after [onResume][android.app.Activity.onResume] is called.
     */
    RESUMED;

    /**
     * Compares if this State is greater or equal to the given `state`.
     *
     * @param state State to compare with
     * @return true if this State is greater or equal to the given `state`
     */
    public fun isAtLeast(state: State): Boolean {
        return compareTo(state) >= 0
    }
}

其中状态的 int 值越大就表示当前的组件越靠近前台可见可操作,或者也可以说通俗点,生命力越旺盛。

我们再来看看事件:

Kotlin 复制代码
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;

    /**
     * Returns the new [Lifecycle.State] of a [Lifecycle] that just reported
     * this [Lifecycle.Event].
     *
     * Throws [IllegalArgumentException] if called on [.ON_ANY], as it is a special
     * value used by [OnLifecycleEvent] and not a real lifecycle event.
     *
     * @return the state that will result from this event
     */
    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")
        }
   
   // ...    
        
}

上面的 targetStateget() 方法还写了不同的事件处理完成后的状态。

其中还包括以下的几种状态事件的转换方法:

Kotlin 复制代码
// 当前状态回到上一个状态需要执行的事件
@JvmStatic
public fun downFrom(state: State): Event? {
    return when (state) {
        State.CREATED -> ON_DESTROY
        State.STARTED -> ON_STOP
        State.RESUMED -> ON_PAUSE
        else -> null
    }
}

// 进入到当前状态需要执行的事件(状态向上转移,生命力变弱)
@JvmStatic
public fun downTo(state: State): Event? {
    return when (state) {
        State.DESTROYED -> ON_DESTROY
        State.CREATED -> ON_STOP
        State.STARTED -> ON_PAUSE
        else -> null
    }
}

// 当前状态进入到下一个状态,需要执行的事件
@JvmStatic
public fun upFrom(state: State): Event? {
    return when (state) {
        State.INITIALIZED -> ON_CREATE
        State.CREATED -> ON_START
        State.STARTED -> ON_RESUME
        else -> null
    }
}

// 进入到目标状态需要执行的事件(状态向下转移,也就是生命力变强)
@JvmStatic
public fun upTo(state: State): Event? {
    return when (state) {
        State.CREATED -> ON_CREATE
        State.STARTED -> ON_START
        State.RESUMED -> ON_RESUME
        else -> null
    }
}

然后我们再看看 LifecycleRegistry#removeObserver() 方法的实现。

Kotlin 复制代码
override fun removeObserver(observer: LifecycleObserver) {
    enforceMainThreadIfNeeded("removeObserver")
    observerMap.remove(observer)
}

这就比较简单了,校验主线程,然后直接移除。注意这里就没有状态更新了。

LifecycleRegistry 中更新状态的方式有两种,一种是直接更新状态,一种是通过事件去更新状态。

Kotlin 复制代码
open fun handleLifecycleEvent(event: Event) {
    enforceMainThreadIfNeeded("handleLifecycleEvent")
    moveToState(event.targetState)
}

override var currentState: State
    get() = state
    /**
     * Moves the Lifecycle to the given state and dispatches necessary events to the observers.
     *
     * @param state new state
     */
    set(state) {
        enforceMainThreadIfNeeded("setCurrentState")
        moveToState(state)
    }

两种更新状态的方法都会调用 moveToState() 方法。

Kotlin 复制代码
private fun moveToState(next: State) {
    if (state == next) {
        return
    }
    // 如果当前状态是 INITIALIZED 不能够直接更新 DESTROYED 状态.
    check(!(state == State.INITIALIZED && next == State.DESTROYED)) {
        "no event down from $state in component ${lifecycleOwner.get()}"
    }
    // 更新状态
    state = next
    if (handlingEvent || addingObserverCounter != 0) { // 如果其他线程正在处理添加 observer 或者 正在同步状态,跳过处理.
        newEventOccurred = true
        // we will figure out what to do on upper level.
        return
    }
    // 标记正在同步状态到 observer
    handlingEvent = true
    // 同步状态到 observer
    sync()
    // 同步完毕
    handlingEvent = false
    if (state == State.DESTROYED) { // 如果已经 DESTROYED 了,清除所有 observer。
        observerMap = FastSafeIterableMap()
    }
}

同步状态到 observer 的方法是 sync(),添加 observer 的方法中也有调用。

Kotlin 复制代码
// 检查是否状态同步完成
private val isSynced: Boolean
    get() {
        if (observerMap.size() == 0) {
            return true
        }
        // 获取最旧的 observer 的状态
        val eldestObserverState = observerMap.eldest()!!.value.state
        // 获取最新的 observer 的状态
        val newestObserverState = observerMap.newest()!!.value.state
        // 如果最新和最旧的 observer 的状态都和当前 LifecycleRegistry 状态一致,就表示同步完成了
        return eldestObserverState == newestObserverState && state == newestObserverState
    }

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
        // 当前状态小于最旧的 observer 的状态,由最旧 -> 最新 observer 开始同步状态
        if (state < observerMap.eldest()!!.value.state) {
            backwardPass(lifecycleOwner)
        }
        // 当前状态大于最新的 observer 的状态,由最新 -> 最旧 observer 开始同步状态
        val newest = observerMap.newest()
        if (!newEventOccurred && newest != null && state > newest.value.state) {
            forwardPass(lifecycleOwner)
        }
    }
    newEventOccurred = false
}

状态同步的顺序分为两个方向,对应的方法是 forwardPass()backwardPass(),我们以 forwardPass() 方法为例子来看看。

Kotlin 复制代码
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)
        ) { // 当前状态大于 observer 的状态,执行循环处理事件下发
            pushParentState(observer.state)
            // 获取更新到下一个状态需要的事件
            val event = Event.upFrom(observer.state)
                ?: throw IllegalStateException("no event up from ${observer.state}")
            // 下发事件    
            observer.dispatchEvent(lifecycleOwner, event)
            popParentState()
        }
    }
}

事件下发会调用 ObserverWitdhState#dispatchEvent() 方法:

Kotlin 复制代码
internal class ObserverWithState(observer: LifecycleObserver?, initialState: State) {
    var state: State
    var lifecycleObserver: LifecycleEventObserver

    init {
        lifecycleObserver = Lifecycling.lifecycleEventObserver(observer!!)
        state = initialState
    }

    fun dispatchEvent(owner: LifecycleOwner?, event: Event) {
        val newState = event.targetState
        state = min(state, newState)
        lifecycleObserver.onStateChanged(owner!!, event)
        state = newState
    }
}

假如我们使用的是 DefaultLifecycleObserver 监听生命周期,那么代码就会走到下面这部分代码:

Kotlin 复制代码
internal class DefaultLifecycleObserverAdapter(
    private val defaultLifecycleObserver: DefaultLifecycleObserver,
    private val lifecycleEventObserver: LifecycleEventObserver?
) : LifecycleEventObserver {
    override fun onStateChanged(source: LifecycleOwner, event: Lifecycle.Event) {
        when (event) {
            Lifecycle.Event.ON_CREATE -> defaultLifecycleObserver.onCreate(source)
            Lifecycle.Event.ON_START -> defaultLifecycleObserver.onStart(source)
            Lifecycle.Event.ON_RESUME -> defaultLifecycleObserver.onResume(source)
            Lifecycle.Event.ON_PAUSE -> defaultLifecycleObserver.onPause(source)
            Lifecycle.Event.ON_STOP -> defaultLifecycleObserver.onStop(source)
            Lifecycle.Event.ON_DESTROY -> defaultLifecycleObserver.onDestroy(source)
            Lifecycle.Event.ON_ANY ->
                throw IllegalArgumentException("ON_ANY must not been send by anybody")
        }
        lifecycleEventObserver?.onStateChanged(source, event)
    }
}

上面的代码就不用多解释了,这样我们上面添加的 observer 就可以获取到生命周期的更新了。

控制 LifecycleRegistry 状态更新

在上面的我们知道了 LifecycleRegistry 如何更新状态,以及如何将状态同步至 Observer。还有一个重要的问题,是谁在控制 LifecycleRegistry 的状态呢??

答案在 androidx.activity.ComponentActivity#onCreate() 生命周期回调中。

Kotlin 复制代码
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)
    ReportFragment.injectIfNeededIn(this)
    if (contentLayoutId != 0) {
        setContentView(contentLayoutId)
    }
}

这里会调用 ReportFragment.injectIfNeededIn(this) 方法去监听 Actvitiy 的生命周期。

Kotlin 复制代码
@JvmStatic
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
    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()
    }
}

这里分为两种情况,当当前设备 Android 版本大于等于 29 时,已经提供了 Activity 生命周期监控的专门 API;其他情况通过 ReportFragment 去监控 Activity 生命周期了。

先看看 API 29 的处理方法:

kotlin 复制代码
@RequiresApi(29)
internal class LifecycleCallbacks : Application.ActivityLifecycleCallbacks {
    override fun onActivityCreated(
        activity: Activity,
        bundle: Bundle?
    ) {}

    override fun onActivityPostCreated(
        activity: Activity,
        savedInstanceState: Bundle?
    ) {
        dispatch(activity, Lifecycle.Event.ON_CREATE)
    }

    override fun onActivityStarted(activity: Activity) {}

    override fun onActivityPostStarted(activity: Activity) {
        dispatch(activity, Lifecycle.Event.ON_START)
    }

    override fun onActivityResumed(activity: Activity) {}

    override fun onActivityPostResumed(activity: Activity) {
        dispatch(activity, Lifecycle.Event.ON_RESUME)
    }

    override fun onActivityPrePaused(activity: Activity) {
        dispatch(activity, Lifecycle.Event.ON_PAUSE)
    }

    override fun onActivityPaused(activity: Activity) {}

    override fun onActivityPreStopped(activity: Activity) {
        dispatch(activity, Lifecycle.Event.ON_STOP)
    }

    override fun onActivityStopped(activity: Activity) {}

    override fun onActivitySaveInstanceState(
        activity: Activity,
        bundle: Bundle
    ) {}

    override fun onActivityPreDestroyed(activity: Activity) {
        dispatch(activity, Lifecycle.Event.ON_DESTROY)
    }

    override fun onActivityDestroyed(activity: Activity) {}

    companion object {
        @JvmStatic
        fun registerIn(activity: Activity) {
            activity.registerActivityLifecycleCallbacks(LifecycleCallbacks())
        }
    }
}

事件更新调用了 dispatch() 方法:

Kotlin 复制代码
@JvmStatic
internal 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).lifecycle
        if (lifecycle is LifecycleRegistry) {
            lifecycle.handleLifecycleEvent(event)
        }
    }
}

最后会调用到我们上面说的 LifecycleRegistry#handleLifecycleEvent() 方法。

再看看 API 29 之前的版本如何处理:

Kotlin 复制代码
open class ReportFragment() : android.app.Fragment() {
    private var processListener: ActivityInitializationListener? = null

    private fun dispatchCreate(listener: ActivityInitializationListener?) {
        listener?.onCreate()
    }

    private fun dispatchStart(listener: ActivityInitializationListener?) {
        listener?.onStart()
    }

    private fun dispatchResume(listener: ActivityInitializationListener?) {
        listener?.onResume()
    }

    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
    }

    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.injectIfNeededIn
            dispatch(activity, event)
        }
    }

    fun setProcessListener(processListener: ActivityInitializationListener?) {
        this.processListener = processListener
    }

    interface ActivityInitializationListener {
        fun onCreate()
        fun onStart()
        fun onResume()
    }
}    

代码也很简单,通过 Fragment 去监控 Activity 的生命周期也都是基本操作了,很多库都这么做,最后也是通过 dispatch() 方法更新状态。

自定义 LifecycleOwner

Android 开发中真的是随处可见 Lifecycle,很多库对 Lifecycle 也有扩展,比如协程。但是我想要我们自己的组件也支持 Lifecycle 要怎么做呢??? 我以为了让 RecyclerView.Adapter 支持 Lifecycle 代码就可以这么写:

Kotlin 复制代码
class MyAdapter : RecyclerView.Adapter<RecyclerView.ViewHolder>(), LifecycleOwner {

    override val lifecycle: Lifecycle
        get() =  lifecycleRegistry
    
    private val lifecycleRegistry: LifecycleRegistry = LifecycleRegistry(this)
    
    init {
        dispatchEvent(Lifecycle.Event.ON_CREATE)
    }

    override fun onAttachedToRecyclerView(recyclerView: RecyclerView) {
        super.onAttachedToRecyclerView(recyclerView)
        dispatchEvent(Lifecycle.Event.ON_RESUME)
    }

    override fun onViewDetachedFromWindow(holder: RecyclerView.ViewHolder) {
        super.onViewDetachedFromWindow(holder)
        dispatchEvent(Lifecycle.Event.ON_PAUSE)
    }
    
    
    fun release() {
        dispatchEvent(Lifecycle.Event.ON_DESTROY)
    }

    private fun dispatchEvent(event: Lifecycle.Event) {
        lifecycleRegistry.handleLifecycleEvent(event)
    }
    
    // ...
}

这里还有一点要注意的是状态为 Destoryed 后,就不能够再使用了。

相关推荐
雨白4 小时前
实现双向滑动的 ScalableImageView(下)
android
峥嵘life4 小时前
Android Studio新版本编译release版本apk实现
android·ide·android studio
studyForMokey6 小时前
【Android 消息机制】Handler
android
敲代码的鱼哇6 小时前
跳转原生系统设置插件 支持安卓/iOS/鸿蒙UTS组件
android·ios·harmonyos
翻滚丷大头鱼6 小时前
android View详解—动画
android
我是好小孩6 小时前
[Android]RecycleView的item用法
android
胖虎17 小时前
Android Studio 读取本地文件(以 ZIP 为例)
android·ide·android studio·本地文件·读取本地文件
出海小纸条7 小时前
Google Play 跨应用脚本漏洞(Cross-App Scripting)
android
小孔龙7 小时前
Android Runtime(ART) GC 日志手册
android