Custom view lifecycle when device screen is locked

136 Views Asked by At

I have a custom view where I want to do some actions when it gets visible or invisible to the user.

I know I can override onVisibilityChanged(changedView: View, visibility: Int) or onDetachedFromWindow functions. But these are not called when the screen is visible and user locks the device with power button. On the other hand Fragment's onStop is called.

Is it somehow possible to detect something like onStop() lifecycle callback in custom view without observing parent lifecycle in this custom view by lifecycle.addObserver(this)?

My use case:

I have a RecyclerView with custom views. They contain ExoPlayer instance where video is played. I need to release the player instance when it is scrolled out or fragment is changed. For this I use:

override fun onDetachedFromWindow() {
   super.onDetachedFromWindow()
   binding.playerView.player?.release()
   binding.playerView.player = null
}

override fun onWindowVisibilityChanged(visibility: Int) {
   super.onWindowVisibilityChanged(visibility)
   if (visibility == VISIBLE) {
      setPlayer()
   }
   if (visibility == GONE  || visibility == INVISIBLE) {
      binding.playerView.player?.release()
      binding.playerView.player = null
   }
}

But the player is not released when I lock the screen.

Note that on Android 12 it is working well as it calls onWindowVisibilityChanged. But devices with Android 11 or lower are not calling this function and keeps the player active.

0

There are 0 best solutions below