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

相关推荐
千里马学框架2 小时前
app性能优化:优化布局层次结构
android·面试·性能优化·framework·分屏·布局·小米汽车
dustcell.2 小时前
高性能web服务器
android·服务器·前端
zh_xuan2 小时前
React Native Demo
android·javascript·react native·ts
zh_xuan2 小时前
kotlin 挂起函数2
android·kotlin·挂起函数
kyle~2 小时前
MySQL基础知识点与常用SQL语句整理
android·sql·mysql
XiaoLeisj3 小时前
Android RecyclerView 实战:从基础列表到多类型 Item、分割线与状态复用问题
android·java
zh_xuan3 小时前
kotlin async异步协程构建器
android·kotlin·协程
阿林来了3 小时前
Flutter三方库适配OpenHarmony【flutter_web_auth】— Android 端 Chrome Custom Tabs 实现分析
android·chrome·flutter
zh_xuan5 小时前
kotlin Channel的用法
android·kotlin·协程·channel