实现后台播放

在 TV 设备上观看内容的用户可能会随时决定切换到 TV 启动器。如果用户在使用 TV 播放应用时切换到启动器,默认情况下,此应用会暂停。由于用户没有明确要求暂停播放,因此这种默认行为可能会显得非常突然而且出乎意料。本课程介绍如何在您的应用中启用后台播放功能,以提供更好的用户体验。

requestVisibleBehind() 方法在 API 级别 26 中已被弃用。
该方法将在未来版本中移除。Android 版本 8.0 及更高版本中不支持本页面中介绍的功能。

请求后台播放

通常,在用户点击主屏幕以显示 TV 启动器后,Activity 便会暂停。但是,您的应用可以请求后台播放,此时 Activity 会在 TV 启动器后面继续播放。

如需请求后台播放,请调用 requestVisibleBehind()。如果 Activity 不再可见,请务必清理媒体资源。例如,如果 requestVisibleBehind() 返回 false 表示请求失败,或者系统调用 onVisibleBehindCanceled() 的替代方法,应释放媒体资源。

Kotlin

    override fun onPause() {
        super.onPause()
        if (videoView?.isPlaying == true) {
            // Argument equals true to notify the system that the activity
            // wishes to be visible behind other translucent activities
            if (!requestVisibleBehind(true)) {
                // App-specific method to stop playback and release resources
                // because call to requestVisibleBehind(true) failed
                stopPlayback()
            }
        } else {
            // Argument equals false because the activity is not playing
            requestVisibleBehind(false)
        }
    }

    override fun onVisibleBehindCanceled() {
        // App-specific method to stop playback and release resources
        stopPlayback()
        super.onVisibleBehindCanceled()
    }
    

Java

    @Override
    public void onPause() {
      super.onPause();
      if (videoView.isPlaying()) {
        // Argument equals true to notify the system that the activity
        // wishes to be visible behind other translucent activities
        if (! requestVisibleBehind(true)) {
          // App-specific method to stop playback and release resources
          // because call to requestVisibleBehind(true) failed
          stopPlayback();
        }
      } else {
        // Argument equals false because the activity is not playing
        requestVisibleBehind(false);
      }
    }

    @Override
    public void onVisibleBehindCanceled() {
      // App-specific method to stop playback and release resources
      stopPlayback();
      super.onVisibleBehindCanceled();
    }