Search code examples
androidandroid-lifecycle

How can lifecycle aware components using LifecycleObserver be aware of screen orientation changes


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

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.

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


Solution

  • 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.

    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
    }