Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cache and Save All Image Conten In WebView From Url And Load It

I have Web Application runs in Android. I can cache my web, so if user has not internet connection, he can still access web from cache. But it only run when user has not Internet Connection.

Now, for optimzing my apps, when user has internet connection, I want to cache all image that show in WebView And store it locally/cache it, and when user open a page with same src image that I have cached it, it load from local, not load it from web again. Or May be not image, but html page that visited cache it, and when user back to url page again, Webview load it from local, not from internet.

I have search the code for two days but still no finding solution.

Thanks for help.

like image 932
Mukhlis Saputro Avatar asked Jan 06 '23 16:01

Mukhlis Saputro


1 Answers

Try this

private void enableWVCache() {

      webView.getSettings().setDomStorageEnabled(true);

      // Set cache size to 8 mb by default. should be more than enough
      webView.getSettings().setAppCacheMaxSize(1024*1024*8);

      File dir = getCacheDir();
      if (!dir.exists()) {
            dir.mkdirs();
         }
      webView.getSettings().setAppCachePath(dir.getPath());
      webView.getSettings().setAllowFileAccess(true);
      webView.getSettings().setAppCacheEnabled(true);

      webView.getSettings().setCacheMode(WebSettings.LOAD_DEFAULT);
}

and then

if ( !isNetworkAvailable() ) { // loading offline
webView.getSettings().setCacheMode( WebSettings.LOAD_CACHE_ELSE_NETWORK );

}

and the method isNetworkAvailable() checks for an active network connection:

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

Finally, don't forget to add the following three permissions to your AndroidManifest.xml:

<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
like image 177
sayan Avatar answered Jan 19 '23 01:01

sayan