设备屏幕锁定时的自定义视图生命周期

发布于 2025-01-15 08:39:56 字数 1064 浏览 3 评论 0原文

我有一个自定义视图,当它对用户可见或不可见时,我想在其中执行一些操作。

我知道我可以重写 onVisibilityChanged(changedView: View,visibility: Int) 或 onDetachedFromWindow 函数。但是,当屏幕可见并且用户使用电源按钮锁定设备时,不会调用这些方法。另一方面,Fragment 的 onStop 被调用。

是否可以在自定义视图中检测诸如 onStop() 生命周期回调之类的内容,而无需通过 lifecycle.addObserver(this) 在此自定义视图中观察父生命周期?

我的用例:

我有一个带有自定义视图的RecyclerView。它们包含播放视频的 ExoPlayer 实例。当播放器实例滚动或片段更改时,我需要释放它。为此,我使用:

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
   }
}

但是当我锁定屏幕时,播放器不会被释放。

请注意,在 Android 12 上它运行良好,因为它调用 onWindowVisibilityChanged。但运行 Android 11 或更低版本的设备不会调用此函数并保持播放器处于活动状态。

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文