从Url缓存并保存WebView中的所有图像并加载它 [英] Cache and Save All Image Conten In WebView From Url And Load It

查看:133
本文介绍了从Url缓存并保存WebView中的所有图像并加载它的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Android中运行Web应用程序。我可以缓存我的网页,所以如果用户没有网络连接,他仍然可以从缓存中访问网页。 但它仅在用户没有互联网连接时运行

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.

现在,为了优化我的应用,当用户有互联网连接时,我想缓存显示在 WebView 中的所有图像并将其存储在本地/缓存它,当用户打开一个具有相同src图像的页面时,我已缓存它,它从本地加载,而不是再次从Web加载。或者可能不是图像,但 html 访问缓存它的页面,当用户再次返回到url页面时, Webview 从本地加载,而不是从互联网加载。

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.

感谢您的帮助。

推荐答案

试试这个

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);
}

然后

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

}

和方法 isNetworkAvailable()检查活动网络连接:

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();
}

最后,不要忘记将以下三个权限添加到 AndroidManifest.xml

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

这篇关于从Url缓存并保存WebView中的所有图像并加载它的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆