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的生命周期方法了

相关推荐
mygljx5 小时前
【MySQL 的 ONLY_FULL_GROUP_BY 模式】
android·数据库·mysql
冬奇Lab7 小时前
AudioTrack音频播放流程深度解析
android·音视频开发·源码阅读
青莲8439 小时前
查找算法详解
android·前端
青莲8439 小时前
排序算法详解
android·前端
zd20057210 小时前
用摩斯密码「听」时间:一款安卓报时应用的诞生
android
不会写代码的猴子10 小时前
Android17版本更新预览
android·android studio
用户416596736935512 小时前
记一次深坑:RecyclerView + FlexboxLayoutManager 导致 canScrollVertically 误判的剖析与修复
android
Be for thing12 小时前
Android 音频硬件(Codec / 喇叭 / 麦克风)原理 + 功耗与问题定位实战(手机 / 手表通用)
android·学习·智能手机·音视频
吉哥机顶盒刷机12 小时前
S905L3A/L3AB芯片迎来安卓14新纪元:Sicha移植版固件深度评测与刷机指南
android·经验分享·刷机