直接访问file:///是不可以的,webview会因为安全问题拦截掉,官方推荐WebViewAssetLoader
import android.webkit.MimeTypeMap;
import android.webkit.WebResourceResponse;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.webkit.WebViewAssetLoader;
import java.io.FileInputStream;
//首先要集成androidx.webkit:webkit:1.4.0
public class SdcardStoragePathHandler implements WebViewAssetLoader.PathHandler {
@Nullable
@Override
public WebResourceResponse handle(@NonNull String filePath) {
String extension = MimeTypeMap.getFileExtensionFromUrl(filePath);
String mimeType = MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension);
try {
return new WebResourceResponse(mimeType, "UTF-8", new FileInputStream(filePath));
} catch (Exception e) {
return null;
}
}
}
webviewClient里拦截即可
webView.webViewClient = object : WebViewClient() {
private val webViewAssetLoader = WebViewAssetLoader.Builder().addPathHandler("/sdcard/", SdcardStoragePathHandler()).build()
override fun shouldInterceptRequest(webView: WebView?, url: String?): WebResourceResponse? {
return url?.let(Uri::parse)?.let(webViewAssetLoader::shouldInterceptRequest) ?: WebViewCacheInterceptorInst.getInstance().interceptRequest(url)
}
override fun shouldInterceptRequest(webView: WebView?, webResourceRequest: WebResourceRequest?): WebResourceResponse? {
return webResourceRequest?.url?.let(webViewAssetLoader::shouldInterceptRequest) ?: WebViewCacheInterceptorInst.getInstance().interceptRequest(webResourceRequest)
}
}
demoH5
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<video controls src="https://appassets.androidplatform.net/sdcard/storage/emulated/0/1658555194419.mp4" width="400" height="200" autoplay>
</video>
<img src="https://appassets.androidplatform.net/sdcard/storage/emulated/0/u.jpg"/>
</body>
</html>
附:如果部分安卓板播放视频报错"setDataSource failed status:0x80000000"但是img是正常显示的,则有可能是安卓板webview.apk版本过低有bug引起的,升级webview.apk版本就可以了。
webview.apk下载地址
https://www.apkmirror.com/uploads/?q=android-system-webview
该网址需要特殊访问,诸君自己努力吧!