由于我的原始答案已降级为评论,因此我将尝试使用新答案进行回复。我不知道为什么,但我现在确实有针对 API 10 及以下以及 API 11 及以上的解决方案。我将发布代码以澄清。
对于 API 11 及以上版本,只需在您的 webview 客户端中覆盖 ShouldInterceptRequest,
对于 API 10 及以下使用此 http 侦听器 http://elonen.iki.fi/code/nanohttpd/,
将这两种方法放在一起,对我来说相关的代码是:
final String assetPrefix = "file:///android_asset/";
final String httpPrefix = "http://localhost:8001";
// for me this part is in onCreateView after the webview settings bit...
{
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB)
webView.setWebViewClient(new HoneyCombWebViewClient());
else
webView.setWebViewClient(new MyWebViewClient());
webViewLoadUrl();
}
private void webViewLoadUrl() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
curURL = assetPrefix + curFileName;
webView.loadUrl(curURL);
}
else
{
curURL = httpPrefix + '/' + curFileName;
String str = assetFileToString(curFileName);
webView.loadDataWithBaseURL(httpPrefix, str, "text/html", "UTF-8", null);
}
}
// then for the WebViewClient
private class HoneyCombWebViewClient extends MyWebViewClient {
public WebResourceResponse shouldInterceptRequest(WebView view, String url)
{
// remove the asset prefix from the url
String fileName = url.substring(assetPrefix.length() - 1);
// ExpansionFiles is the pointer to your ZipResourceFile
InputStream inputStream = ExpansionFiles.getWebResource(fileName);
if (url.endsWith("jpg") || url.endsWith("png"))
return new WebResourceResponse("image/*", "base64", inputStream);
return super.shouldInterceptRequest(view, url);
}
}
private class MyWebViewClient extends WebViewClient {
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
else if (url.startsWith(httpPrefix)) {
curURL = url;
String str = assetFileToString(url.substring(httpPrefix.length() + 1));
webView.loadDataWithBaseURL(httpPrefix, str, "text/html", "UTF-8", null);
return true;
}
else if (url.startsWith(assetPrefix)){
curURL = url;
view.loadUrl(url);
return true;
}
// else.....
}
}
最后,要使用 NanoHTTPD,找到方法 serve 并将输入流从扩展文件返回到您的文件:
public Response serve( String uri, String method, Properties header, Properties parms, Properties files )
{
InputStream data = ExpansionFiles.getWebResource(uri);
String mimeType;
if (uri.endsWith("jpg") || uri.endsWith("png"))
mimeType = "base64";
else if (uri.endsWith("css"))
mimeType = "text/css";
else if (uri.endsWith("js"))
mimeType = "text/javascript";
else
mimeType = "text/html";
return new Response( HTTP_OK, mimeType, data );
}
在顶层某处调用构造函数:
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB) {
// this for loading images from expansion file under webview in API 10
try
{
webServer = new NanoHTTPD(8001, new File("."));
}
catch( IOException ioe )
{
System.err.println( "Couldn't start server:\n" + ioe );
System.exit( -1 );
}
}
哦,你需要从 NanoHTTPD 中删除 main 方法
我希望你觉得这有帮助。对我来说这是一个漫长而痛苦的过程......