我正在尝试缓存 WebView 中加载的网站,但如果网络连接关闭,我将无法使其工作。
Cachdirectory 已创建,缓存文件就在那里。已授予权限。我加载网页然后关闭网络(也给出了 WI-FI 权限),当我尝试重新加载页面时出现错误(现在应该从缓存加载)。请帮忙!
这是代码:
WebView engine=(WebView)findViewById(R.id.web_engine);
engine.getSettings().setJavaScriptEnabled(true);
engine.getSettings().setBuiltInZoomControls(true);
engine.getSettings().setLoadsImagesAutomatically(true);
engine.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
engine.setInitialScale(1);
engine.setWebViewClient(new WebViewClient());
engine.setWebChromeClient(new WebChromeClient()
{
@Override
public void onReachedMaxAppCacheSize(long spaceNeeded, long totalUsedQuota,QuotaUpdater quotaUpdater)
{
quotaUpdater.updateQuota(spaceNeeded * 2);
}
public void onProgressChanged(WebView view, int progress)
{
activity.setTitle("Loading...");
activity.setProgress(progress * 100);
if(progress == 100)
{
activity.setTitle(R.string.app_name);
}
}
});
String appCachePath;
engine.getSettings().setDomStorageEnabled(true);
// Set cache size to 8 mb by default. should be more than enough
engine.getSettings().setAppCacheMaxSize(1024*1024*8);
appCachePath = getApplicationContext().getCacheDir().getAbsolutePath();
engine.getSettings().setAppCachePath(appCachePath);
engine.getSettings().setAllowFileAccess(true);
engine.getSettings().setAppCacheEnabled(true);
engine.getSettings().setCacheMode(WebSettings.LOAD_DEFAULT);
cm = (ConnectivityManager) this.getSystemService(Activity.CONNECTIVITY_SERVICE);
if(cm.getActiveNetworkInfo() == null || !cm.getActiveNetworkInfo().isConnected())
{
appCachePath = getApplicationContext().getCacheDir().getAbsolutePath();
engine.getSettings().setAppCachePath(appCachePath);
engine.getSettings().setCacheMode(WebSettings.LOAD_DEFAULT);
engine.loadUrl("http://www.google.com");
}
else
{
System.err.println("CACHE OR NETWROK");
engine.getSettings().setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);
engine.loadUrl("http://www.google.com");
}
}
和权限:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<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" />
您的使用
engine.getSettings().setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);
告诉 WebView 从缓存加载页面,但如果它需要缓存中没有的内容,它会查找网络,当您没有连接时,它只会给您“页面无法加载”错误”。这是因为遗憾的是,并非所有内容都存储在缓存中,即使使用此设置,您也会注意到浏览器使用网络。
让 WebView 忽略无连接的唯一方法是使用
engine.getSettings().setCacheMode(WebSettings.LOAD_CACHE_ONLY);
设置代替。某些图像不会使用此设置加载(因为它们没有缓存),但它仍然会加载在缓存中找到的所有内容。
与您的问题无关的另一个注意事项是,在您的代码中,您使用了 setAppCacheMaxSize ,并且它在 API 18 及更高版本中已被弃用,因为 WebView 自行管理缓存大小,因此请注意这一点。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)