Android webview播放视频全拼
时间: 2023-10-22 18:03:44 浏览: 45
Android 中的 WebView 播放视频是通过 VideoView 实现的,在 WebView 中播放视频需要以下几个步骤:
1. 配置 WebView 的 settings:
```
webView.settings.javaScriptEnabled = true
webView.settings.pluginState = WebSettings.PluginState.ON
webView.settings.allowFileAccess = true
```
2. 在 WebViewClient 的 shouldOverrideUrlLoading 方法中处理视频链接:
```
override fun shouldOverrideUrlLoading(view: WebView?, url: String?): Boolean {
if (url != null && (url.startsWith("http://") || url.startsWith("https://"))) {
view?.loadUrl(url)
return false
} else {
val intent = Intent(Intent.ACTION_VIEW, Uri.parse(url))
startActivity(intent)
return true
}
}
```
3. 在 WebChromeClient 中实现视频播放:
```
webView.webChromeClient = object : WebChromeClient() {
override fun onShowCustomView(view: View?, callback: CustomViewCallback?) {
super.onShowCustomView(view, callback)
if (view is FrameLayout) {
videoView = VideoView(this@MainActivity)
videoView?.layoutParams = FrameLayout.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.MATCH_PARENT
)
view.addView(videoView)
setContentView(view)
videoView?.setVideoPath(videoUrl)
videoView?.setOnPreparedListener {
videoView?.start()
}
}
}
override fun onHideCustomView() {
super.onHideCustomView()
if (videoView != null) {
videoView?.stopPlayback()
videoView = null
}
setContentView(webView)
}
}
```
其中,onShowCustomView 方法会在 WebView 中播放视频时调用,onHideCustomView 方法会在视频播放结束后调用。
需要注意的是,Android 7.0 以上需要在 AndroidManifest.xml 文件中添加以下代码来允许应用播放 HTTP 和 HTTPS 视频:
```
<application
...
android:usesCleartextTraffic="true">
...
</application>
```
以上就是 Android WebView 播放视频的全拼了。