赞
踩
Android 端加载 html 方式
wv.loadUrl("file:///android_asset/xxx/xxx/index.html");
Javascript 引用 assert 中的资源, 路径需要预先约定好
<link rel="xxx" href="/android_asset/xxx/xxx.js">
Android端加载 html 方式
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); } }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。