本文介绍了使用 LifecycleObserver 的生命周期感知组件如何感知屏幕方向变化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用 LifecycleObserver 制作生命周期感知组件非常容易,例如当用户离开屏幕时暂停和停止 MediaPlayer.

Making a lifecycle aware component is super easy with LifecycleObserver e.g. pausing and stopping MediaPlayer when the user is leaving the screen.

但是有什么方法可以让我知道生命周期是否正在经历 onPauseonStop 等,只是因为配置更改正在发生?在那种情况下,我不会对 MediaPlayer 做任何事情.在 Fragment 中有 activity?.isChangingConfiguration() 但在 LifecycleObserver 中,据我所知,我没有得到这样的信息?

But is there any way for me to know if the lifecycle is going through onPause, onStop etc. just because a configuration change is happening? In that case, I wouldn't do anything to the MediaPlayer. In Fragment there is activity?.isChangingConfiguration() but in LifecycleObserver I don't get such information as far as I'm aware?

class AudioPlayerLifecycleObserver(private val mediaPlayer: MediaPlayer) : LifecycleObserver {
    @OnLifecycleEvent(Lifecycle.Event.ON_PAUSE)
    fun onPause() {
        // Media player will pause even if the screen is just changing orientation
        mediaPlayer.pause()
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_STOP)
    fun onStop() {
        // Media player will stop even if the screen is just changing orientation
        mediaPlayer.stop()
    }

}

媒体播放器停止和暂停仅用于演示目的.

Media player stop and pause is used just for demonstrative purposes.

请注意,所考虑的架构是 MVVM,因此传递对片段的弱引用是不可取的.

Note that the architecture in mind is MVVM so passing a weak reference to fragment around is undesirable.

推荐答案

原来生命周期事件函数可以接收一个 lifecycleOwner 作为参数.我不知道这个存在,没有找到官方文档,我的一个同事告诉我这个并且它有效.

Turns out lifecycle event functions can receive a lifecycleOwner as a parameter. I didn't know this existed, didn't find official docs on it, a colleague of mine told me about this and it works.

无论如何,只需检查 lifecycleOwnerFragment 还是 Activity,然后调用 activity?.isChangingConfiguration> 或 isChangingConfiguration.

Anyway simply check if the lifecycleOwner is a Fragment or an Activity and then call either activity?.isChangingConfiguration or isChangingConfiguration.

简而言之,这样的事情会起作用:

In short, something like this would work:

@OnLifecycleEvent(Lifecycle.Event.ON_STOP)
fun onStop(lifecycleOwner: LifecycleOwner) {
    // Cast lifecycleOwner to Fragment or Activity and use isChangingConfiguration
}

这篇关于使用 LifecycleObserver 的生命周期感知组件如何感知屏幕方向变化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

06-14 20:15