了解Android WebView是否显示缓存页面

asc*_*scu 7 android caching webview

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

有没有办法找出所显示的页面是否已从服务器或缓存中获取?

甚至可能是缓存页面的年龄.

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

Tho*_*ler 8

你可以尝试一个黑客-在第一组的WebView 缓存模式WebSettings.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);
Run Code Online (Sandbox Code Playgroud)