Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find out if Android WebView is showing cached page

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.

like image 245
ascu Avatar asked May 25 '11 13:05

ascu


People also ask

How do I check my WebView cache?

webview cache is saved into /data/data/[your_package_name]/cache/org.

How do I disable cache in WebView?

Just after creating your webview, before loading any pages, you can clear the cache. myBrowser. clearCache(true) - the boolean indicates if you wish to delete the cached files on disk as well.

Is WebView slower than browser?

Web View is slower on both as compared to native android browser.

Which view displays web pages in Android?

WebView is a view that display web pages inside your application. You can also specify HTML string and can show it inside your application using WebView. WebView makes turns your application to a web application.


1 Answers

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);
like image 112
Thomas Keller Avatar answered Sep 22 '22 22:09

Thomas Keller