44

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

 4 years ago
source link: https://droidyue.com/blog/2020/02/09/play-audio-or-video-background-in-webview-app-android/?
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

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 androidyue Feb 9th, 2020Android, Audio, Background, Video, WebView, 后台, 网页, 视频, 音频

« Mac下实现超快捷切换DNS 修复 LC_CTYPE LC_ALL 设置问题 »

droidyue_gzh_green_png.png
0 comments

Be the first person to leave a comment!


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK