2011-05-25 94 views
6

我正在制作一个Android应用程序,其中包括在webview中显示网站。据我所知,如果无法建立连接,webview会自动显示缓存的页面版本。找出Android WebView是否显示缓存页面

有什么方法可以找出显示的页面是否从服务器或缓存中获取?

甚至可能是缓存页面的大小。

这是为了能够通知用户他/她是否正在查看旧信息。

回答

7

你可以尝试破解 - 在第一组的WebView cache modeWebSettings.NO_CACHE并加载URL。然后,创建一个像这样的自定义WebChromeClient:

final String urlToLoad = "http://www.my-url.com"; 
webview.setWebViewClient(new WebViewClient() { 
    @Override 
    public void onReceivedError(WebView view, int errorCode, 
      String description, String failingUrl) 
    { 
     if (view.getSettings().getCacheMode() == WebSettings.LOAD_NO_CACHE && urlToLoad.equals(failingUrl)) 
     { 
      view.getSettings().setCacheMode(WebSettings.LOAD_CACHE_ONLY); 
      view.loadUrl(urlToLoad); 
      return; 
     } 
     else 
     if (urlToLoad.equals(failingUrl)) 
     { 
      // cache failed as well, load a local resource as last resort 
      // or inform the user 
     } 
     super.onReceivedError(view, errorCode, description, failingUrl); 
    } 
}); 
webview.loadUrl(urlToLoad); 
+0

这仍然是这样的黑客攻击。为什么没有办法检查给定URL是否存在缓存?编辑:为什么Android如果缓存存在调用onReceivedError()? – mhenry 2012-03-05 23:40:27

0

由于WebView像浏览器一样工作,答案是否定的。 有一些黑客的方式来检测这种情况。

或另一种解决办法来防止页面被缓存(见的WebView文档)