Android WebView 播放視訊無法播放問題和視訊適應螢幕大小
阿新 • • 發佈:2019-02-04
1.視訊無法播放:
點選播放按鈕後,提示視訊載入失敗,錯誤碼0_4
解決這個問題需要新增以下程式碼:
在AndroidManifest中
android:hardwareAccelerated="true"
在設定webview程式碼中新增
//支援視訊播放 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { webView.getSettings().setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW); } webView.getSettings().setPluginState(WebSettings.PluginState.ON); webView.getSettings().setUseWideViewPort(true); // 關鍵點 webView.getSettings().setAllowFileAccess(true); // 允許訪問檔案 webView.getSettings().setSupportZoom(true); // 支援縮放 webView.getSettings().setLoadWithOverviewMode(true); webView.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE); // 不載入快取內容
視訊播放正常了:
2.但是我們發現視訊的尺寸有點大,超過了螢幕的寬度,怎麼辦呢?
其實這裡要用到web的css程式碼
在html程式碼中新增以下樣式:
iframe {
display: block;
max-width:100%;
margin-top:10px;
margin-bottom:10px;
}
iframe是獲取的html程式碼中巢狀視訊的標籤,要對應起來
具體程式碼:
//官方適應螢幕 private String getHtmlData(String bodyHTML) { String head = "<head>" + "<meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0, user-scalable=no\"> " + "<style type=\"text/css\"> body { line-height:"+(150)+"%} </style> \n" + "<style>img{max-width: 100%; width:auto; height:auto;}</style>" + //圖片適應螢幕 "<style>iframe {display: block;max-width:100%;\n" + //視訊適應螢幕 " margin-top:10px; margin-bottom:10px;}</style>" + "<style type=\"text/css\"> \n" + "</style> \n" + "</head>"; String htmlStr = "<html>" + head + "<body>" + bodyHTML + "</body></html>"; return htmlStr; }
視訊大小顯示就正常了: