Tags
androidapp
Created
Feb 26, 2020 3:52 AM
技术小黑屋
Navigate…
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"
}
}
}
|
完整示例项目
Posted by androidyueFeb 9th, 2020 Android, Audio, Background, Video, WebView, 后台, 网页, 视频, 音频 « Mac下实现超快捷切换DNS 修复 LC_CTYPE LC_ALL 设置问题 »
优质知识付费
commentsAnonymous
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 阿里云