简体   繁体   中英

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.

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"/>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM