我有一个应用程序,在Android WebViewClient的
shouldInterceptRequest(WebView view,String url)
和shouldOverrideUrlLoading(WebView view,String url)
中使用自定义方案来拦截Web应用程序中的请求,并在shouldInterceptRequest
中使用本地库从其他地方获取资源。这一直运作良好,直到Android 4.4 KitKat,Google对webView组件进行了一些关键更改。
http://developer.android.com/guide/webapps/migrating.html#URLs
现在在shouldOverrideUrlLoading
中接收到的URL突然变成无效的,看起来像这样:custom-scheme:////my.pathname.com/。起初我怀疑额外的斜杠是因为Android认为URL不符合RFC3986标准,但在一系列资源获取(CSS、JS、图像)中,URL一开始是正确的,然后突然变成无效格式。 Android 4.3中的webView将URL正确保留为custom-scheme://my.pathname.com/。似乎基本URL突然更改为“/'而不是'my.pathname.com'。
然后我的注意力转向webView 4.4迁移指南所提到的:
如果您从任何线程调用WebView上的方法而不是您的应用程序的UI线程,则可能会导致意外结果。 http://developer.android.com/guide/webapps/migrating.html#Threads
这也可能是我正在经历的问题,但我还没有想出一个解决方案,在其中我可以使用runOnUiThread()
使用本机API获取数据并将其返回到shouldInterceptRequest
内部的webView。有人遇到过类似的问题吗?
shouldInterceptRequest
代码的简化版本: @Override
public WebResourceResponse shouldInterceptRequest(WebView view, String url) {
if (urlStartsWithKnownPrefix(url)) {
UrlFetchResult fetchRes = api.fetchUrl(url);
String charset = "utf-8";
String mime = fetchRes.getMimetype();
WebResourceResponse res = new WebResourceResponse(mime, charset, new ByteArrayInputStream(fetchRes.getResult()));
return res;
}
return null;
}
loadDataWithBaseURL()
需要一个baseUrl参数,但是该方法用于数据而不是url。对于Android 4.4 WebView在自定义方案上工作,我必须显式设置baseUrl吗?在同一webView中使用http://一切正常,因此Android验证自定义方案与http://不同。 - MartinRonPageStarted(WebView view, String url, Bitmap favicon)
和onPageFinished(WebView view, String url)
方法,我发现它开始的 URL 是 "custom-scheme://my.pathname.com/",结束的 URL 是 "custom-scheme:////my.pathname.com/"。这是一个 bug 吗? - MartinR