Find out if Android WebView is showing cached page

被刻印的时光 ゝ 提交于 2020-01-13 09:02:13

问题


I'm making an Android application that, among other things, shows websites in a webview. As far as I understand, the webview automatically shows a cached version of the page if a connection can't be established.

Is there any way to find out if the page shown has been fetched from the server or cache?

Maybe even how old the cached page is.

This is to be able to notify the user if he/she is viewing old information.


回答1:


You could try a hack - at first set WebView's cache mode to WebSettings.NO_CACHE and load the URL. Then, create a custom WebChromeClient like this:

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);



回答2:


Since the WebView work like the browser the answer is no. There are some hacky way to detect that situation.

Or an alternative solution would be preventing the page from being cached (see WebView documentation)



来源:https://stackoverflow.com/questions/6125597/find-out-if-android-webview-is-showing-cached-page

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!