1. web项目放在assert文件夹下
wv.loadUrl("file:///android_asset/xxx/xxx/index.html");
Javascript 引用 assert 中的资源, 路径需要预先约定好
<link rel="xxx" href="/android_asset/xxx/xxx.js">
2. web 项目放在 外置存储
wv.loadUrl("file:///sdcard/Android/data/xxx/files/Download/xxx/index.html");
Javascript 引用外置存储中的资源, 出于安全的考虑,禁止直接路径的调用,而需要 WebView 做资源拦截,替换为本地资源地址,然后以文件流的方式,回传给前端
WebView wv = find....
WebSettings settings = wv.getSettings();
settings.setJavaScriptEnabled(true);
settings.setAllowFileAccess(true);
settings.setAllowFileAccessFromFileURLs(true);
settings.setAllowContentAccess(true);
settings.setDomStorageEnabled(true);
wv.setWebViewClient(new MyWebViewClient());
public class MyWebViewClient extends WebViewClient {
@Nullable
@Override
public WebResourceResponse shouldInterceptRequest(WebView view, WebResourceRequest request) {
String url = request.getUrl().toString();
InputStream inputStream = null;
String mimeType = "";
if( url.startsWith("file:///assets")) {
if(url.endsWith("js")) {
mimeType = "text/javascript";
} else if(url.endsWith("css")) {
mimeType = "text/css";
} else if(url.endsWith("json")) {
mimeType = "application/json";
} else if(url.endsWith("bin")) {
mimeType = "application/octet-stream";
}
File externalFilesDir = getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS);
String loadPath = url.replace("file:///", externalFilesDir.getAbsolutePath() + File.separator +"dist"+ File.separator);
File loadFile = new File(loadPath);
try {
inputStream = new FileInputStream(loadFile);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
if(inputStream != null) {
Map<String, String> responseHeaders = new HashMap<>();
responseHeaders.put("Connection", "close");
responseHeaders.put("Content-Type", mimeType);
responseHeaders.put("Date", "$dateString GMT");
responseHeaders.put("Access-Control-Allow-Origin", "*");
responseHeaders.put("Access-Control-Allow-Methods", "GET, POST, DELETE, PUT, OPTIONS");
responseHeaders.put("Access-Control-Max-Age", "600");
responseHeaders.put("Access-Control-Allow-Headers", "accept, authorization, Content-Type");
String encoding = "utf-8";
int statusCode = 200;
String reasonPhrase = "SUCCESS";
return new WebResourceResponse(mimeType, encoding, statusCode, reasonPhrase, responseHeaders, inputStream);
}
return super.shouldInterceptRequest(view, request);
}
}
原文地址:https://blog.csdn.net/SeeyouMT/article/details/127888779
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如若转载,请注明出处:http://www.7code.cn/show_37808.html
如若内容造成侵权/违法违规/事实不符,请联系代码007邮箱:suwngjj01@126.com进行投诉反馈,一经查实,立即删除!
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。