Skip to content Skip to sidebar Skip to footer

Cacheing Of Webpage For Offline Use (android)

i am following this question from stack overflow for my query. the code works fine but when in offline mode it does not load any page , instead it shows no internet connection. i a

Solution 1:

As far as I know, WebView loads from cache if web server replies with HTTP 304 (not modified). It still require to send HTTP GET to web server and that requires network connection.

Solution 2:

after doing some research i found answer to my question.

i explicitly downloaded the webpage into the device and save it. and when the device is in offline mode i display the webpage saved in the device. and when it is online the page is again downloaded and override the previous one.

i used the following code-

to download

InputStreaminput=null;
OutputStreamoutput=null;
HttpURLConnectionconnection=null;
       URLurl=newURL("http://192.168.1.210/bibhutest.html");
       connection = (HttpURLConnection) url.openConnection();
       connection.connect();
            intfileLength= connection.getContentLength();
            input = connection.getInputStream();
            output = newFileOutputStream("address at which you want to download file");
            byte data[] = newbyte[4096];
            longtotal=0;
            int count;
            while ((count = input.read(data)) != -1) {
                if (isCancelled()) {
                    input.close();
                    returnnull;
                }
                total += count;
                output.write(data, 0, count);
            }
                if (output != null)
                    output.close();
                if (input != null)
                    input.close();
            if (connection != null)
                connection.disconnect();

to show the downloaded file

if (!isNetworkAvailable()) {
// from the device when dont have internet
webView.loadUrl("file:////sdcard/android/data/downloads.html");
webView.requestFocus();
}

if (!isNetworkAvailable()) {
//load directly from the internet
webView.loadUrl(url);
webView.requestFocus();
}

privatebooleanisNetworkAvailable() {
    ConnectivityManagerconnectivityManager= (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);
    NetworkInfoactiveNetworkInfo= connectivityManager.getActiveNetworkInfo();
    return activeNetworkInfo != null && activeNetworkInfo.isConnected();
}

use the above code according to your own need and tweak it when to download the file and save the file and how to display. apply the appropriate logic in your code.

thank you

Post a Comment for "Cacheing Of Webpage For Offline Use (android)"