Search code examples
androidhtmlwebviewoffline-cachingoffline-mode

displaying cached version of webview in android


I am trying to get the HTML5 offline cached version of a website to display when the network is down inside of a webview.

I have overridden onReceivedError ok, and when the network is down this method is called. Problem is that it displays the generic "Web Page is not available" message.

How can I get it to display the HTML5 cached version of the page? The offline storage of the webapp is definately working, as it works fine in the desktop version of Firefox and Chrome.

I know I can call loadData into the view manually in onReceivedError, but im not sure where I can get the HTML5 cached value from.

Note: If I set some dummy data in loadData such as view.loadData(Uri.encode("<html><div>Page load failed</div></html>"), "text/html", "UTF-8"); and then click back (by detecting back event and calling webview.goBack(); then the cached version of the page is displayed ok.

Here are some lines of code I added to setup the webview:

webview.getSettings().setCacheMode(WebSettings.LOAD_DEFAULT);
webview.getSettings().setAppCacheMaxSize(1024*1024*8);                         
webview.getSettings().setAppCachePath("/data/data/com.stuff.android/cache");
webview.getSettings().setAllowFileAccess(true);
webview.getSettings().setAppCacheEnabled(true);
webview.getSettings().setDomStorageEnabled(true);
webview.getSettings().setJavaScriptEnabled(true);

Solution

  • Try to find out the network status using

    private boolean isNetworkAvailable() {
        ConnectivityManager connectivityManager 
              = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
        return activeNetworkInfo != null;
    }
    

    (Detect whether there is an Internet connection available on Android)

    This also needs

    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    

    in your AndroidManifest.xml

    Now you can set the cache behaviour either to LOAD_CACHE_ONLY or to LOAD_NO_CACHE, depending on whether a network connection is available, with

    webview.getSettings().setCacheMode(...)