Cache and Save All Image Conten In WebView From Ur

2019-03-31 05:26发布

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.

1条回答
走好不送
2楼-- · 2019-03-31 05:49

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"/>
查看更多
登录 后发表回答