WebView播放視頻白屏、不能全屏問題解決


在項目中,會有在webview嵌入的網頁中播放視頻的需求,會在部分手機上出現白屏或有聲音無畫面等問題,並且存在全屏按鈕點擊無效果的問題。

此文章已收入Android偶遇雜症合集(持續更新)

1. 播放視頻白屏、無畫面問題解決

原因是WebView播放視頻時可能需要硬件加速才可以正常播放視頻,關閉硬件加速可能在部分手機上出現白屏、無畫面、無法暫停等問題。解決方法就是開啟硬件加速:

  1. 在AndroidManifest.xml的application中聲明HardwareAccelerate屬性
  2. 在AndroidManifest.xml的對應activity中聲明HardwareAccelerate屬性
  3. 在使用WebView的代碼前添加如下代碼:
window.setFlags(WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED,
		WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED)

2. 視頻不能全屏問題解決

原因是WebView的視頻全屏事件是需要客戶端完成后續邏輯的,網頁點擊全屏按鈕會觸發WebChromeClient的onShowCustomView方法,全屏后縮回來會觸發onHideCustomView方法,在這兩個方法中我們要對視頻進行一個全屏放大的處理。

在我們的WebView使用之前需要添加的代碼如下:

    var fullscreenContainer: FrameLayout? = null
    var customViewCallback: WebChromeClient.CustomViewCallback? = null
    val mWebChromeClient = object : WebChromeClient() {
        override fun onShowCustomView(view: View?, callback: CustomViewCallback?) {
            super.onShowCustomView(view, callback)
            showCustomView(view, callback)
        }

        override fun onHideCustomView() {
            super.onHideCustomView()
            hideCustomView()
        }
    }

    /**
     * 顯示自定義控件
     */
    private fun showCustomView(view: View?, callback: WebChromeClient.CustomViewCallback?) {
        if (fullscreenContainer != null) {
            callback?.onCustomViewHidden()
            return
        }

        fullscreenContainer = FrameLayout(context).apply { setBackgroundColor(Color.BLACK) }
        customViewCallback = callback
        fullscreenContainer?.addView(view)
        val decorView = (context as? Activity)?.window?.decorView as? FrameLayout
        (context as? Activity)?.requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE
        decorView?.addView(fullscreenContainer)
    }

    /**
     * 隱藏自定義控件
     */
    private fun hideCustomView() {
        if (fullscreenContainer == null) {
            return
        }

        val decorView = (context as? Activity)?.window?.decorView as? FrameLayout
        (context as? Activity)?.requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_PORTRAIT
        fullscreenContainer?.removeAllViews()
        decorView?.removeView(fullscreenContainer)
        fullscreenContainer = null
        customViewCallback?.onCustomViewHidden()
        customViewCallback = null
    }

最終在WebView使用時,為WebView設置WebChromeClient:

	webView.webChromeClient = mWebChromeClient


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM