直接访问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
该网址需要特殊访问,诸君自己努力吧!

原文地址:https://blog.csdn.net/hjywyj/article/details/125948785

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。

如若转载,请注明出处:http://www.7code.cn/show_7339.html

如若内容造成侵权/违法违规/事实不符,请联系代码007邮箱:suwngjj01@126.com进行投诉反馈,一经查实,立即删除

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注