Open vvLavida opened 8 years ago
WebResourceResponse(String mimeType, String encoding, InputStream); 其中的MimeType匹配参考:http://stackoverflow.com/a/36278648/1656402
Android 4.4及以上版本,会校验webview加载的URL的有效性。类似_http://10.1.1.x:8080/index.html_的URL加载不会触发shouldOverrideUrlLoading方法。 参考https://developer.android.com/guide/webapps/migrating.html#URLs
解决思路: 使用loadDataWithBaseURL,约定一个「Base URL: http://x.com」,确保shouldOverrideUrlLoading会覆盖执行,然后在回调时将「Base URL」替换掉。 http://stackoverflow.com/questions/31702036/webview-shouldoverrideurlloading-not-getting-called
定制user-scheme(如zl://xxxxx/1234),实现html页面加载离线资源。 如: 页面使用
标签的 src = zl://resourceid/xxxx 访问离线资源file:///android_asset/drawable/test.png"
// 这个回调可以通知主程序WebView处理的资源(css,js,image等)请求,并允许主程序进行处理后返回数据。 // 如果主程序返回的数据为null,WebView会自行请求网络加载资源,否则使用主程序提供的数据。 //(非UI线程) @TargetApi(Build.VERSION_CODES.LOLLIPOP) @Override public WebResourceResponse shouldInterceptRequest(WebView view, WebResourceRequest request) { if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) { return null; } return WebResourceSchemeController.handle(super.shouldInterceptRequest(view, request), request.getUrl().toString()); }
@Override public WebResourceResponse webResourceIntercept() { try { InputStream localCopy = context.getAssets().open("drawable/test.png"); // 页面使用
标签的 src = zl://resourceid/xxxx 访问离线资源file:///android_asset/drawable/test.png"
// url映射到本地路径的页面,在替换scheme之外,还需去掉url所带的参数
response = new WebResourceResponse("image/png", "UTF-8", localCopy);
} catch (IOException e) {
e.printStackTrace();
}
return response;
}