Android Webview 後臺播放音視頻實現

http://droidyue.com/blog/2020/02/09/play-audio-or-video-background-in-webview-app-android/java


問題

  • 咱們使用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"  }  } } 

完整示例項目

相關文章
相關標籤/搜索