Android Webview 后台播放音视频实现 - 技术小黑屋

Published by Xianqiao Wang on February 26th, 2020

Android Webview 后台播放音视频实现

Feb 9th, 2020

问题

  • 我们使用WebView播放音乐或视频(比如油管视频)
  • 前台播放一直很正常,但是比较费电
  • 进入后台后就会暂停播放
  • 所以需求就是我们想要App在后台时同样播放音视频

解决方法

  • 重写onWindowVisibilityChanged方法,让网页任然感觉像是在前台执行。

关键代码


1
2
3
4
5
6
override fun onWindowVisibilityChanged(visibility: Int) {
        super.onWindowVisibilityChanged(View.VISIBLE)

        Log.i("BackgroundMediaWebView", "onWindowVisibilityChanged " +
                "visibility=${toReadableVisibility(visibility)}")
    }
  • 当App 进入后台(按Home键),visibility会变成Gone
  • 我们强制调用super.onWindowVisibilityChanged(View.VISIBLE)会保持WebView继续播放音视频

完整代码


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
package com.example.webviewvisibilitychangedsample

import android.content.Context
import android.util.AttributeSet
import android.util.Log
import android.view.View
import android.webkit.WebView

class BackgroundMediaWebView @JvmOverloads constructor(
    context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0
) : WebView(context, attrs, defStyleAttr) {

    override fun onWindowVisibilityChanged(visibility: Int) {
        super.onWindowVisibilityChanged(View.VISIBLE)

        Log.i("BackgroundMediaWebView", "onWindowVisibilityChanged " +
                "visibility=${toReadableVisibility(visibility)}")
    }

    private fun toReadableVisibility(visibility: Int): String {
        return when(visibility) {
            View.VISIBLE -> "Visible"
            View.INVISIBLE -> "Invisible"
            View.GONE -> "Gone"
            else -> "Unknown"
        }
    }
}

完整示例项目




优质知识付费



0 comments
Anonymous






Markdown is supportedPreviewLogin with GitHub

Be the first person to leave a comment!

最新文章

扫一扫关注小黑屋公众号(droidyue_com)


Copyright © 2020 - androidyue - Powered by Octopress ;优质服务品牌: OneDrive Vultr VPS Digital Ocean 阿里云



https://droidyue.com/blog/2020/02/09/play-audio-or-video-background-in-webview-app-android/?hmsr=toutiao.io&utm_medium=toutiao.io&utm_source=toutiao.io