Android Webview 离线时加载缓存
我有一个从网站加载网址的应用程序。现在我希望应用程序在离线时使用缓存。但我只是收到失败页面,显示我未连接到该网站。起初我将 Cachemode 设置为 Load_Normal 但这没有帮助。接下来,我使用 ConnectivityManager 尝试了一种非常“愚蠢”的方法:
cm = (ConnectivityManager) this.getSystemService(Activity.CONNECTIVITY_SERVICE);
if(cm.getActiveNetworkInfo().isConnected()){
mfnWebView.getSettings().setCacheMode(WebSettings.LOAD_DEFAULT);
mfnWebView.loadUrl(url);
}
else{
mfnWebView.getSettings().setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);
mfnWebView.loadUrl(url);
}
但这只会导致应用程序崩溃。
有没有一种简单的方法可以在离线和存在时加载缓存,如果不存在则显示失败消息。
I have an application which loads urls from a website. Now I want the application to use the cache when offline. But I just get the failure page which says that im not connected to the website. At first I set the Cachemode to Load_Normal but this doesn't help. Next I tried a realy "silly" approach using the ConnectivityManager:
cm = (ConnectivityManager) this.getSystemService(Activity.CONNECTIVITY_SERVICE);
if(cm.getActiveNetworkInfo().isConnected()){
mfnWebView.getSettings().setCacheMode(WebSettings.LOAD_DEFAULT);
mfnWebView.loadUrl(url);
}
else{
mfnWebView.getSettings().setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);
mfnWebView.loadUrl(url);
}
but this just leads to crashing the application.
Is there a simple way to load the cache when offline and existing and just if not existing showing the failure message.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
好的。上面的代码很好。需要添加的权限有:
.INTERNET
.ACCESS_NETWORK_STATE
.ACCESS_WIFI_STATE
OK. The code is fine above. The permission needed to be added are:
.INTERNET
.ACCESS_NETWORK_STATE
.ACCESS_WIFI_STATE
除了另一个答案中提到的权限
.INTERNET
.ACCESS_NETWORK_STATE
.ACCESS_WIFI_STATE
之外,我还需要对代码进行以下更改:
否则,如果我没有连接到任何 WiFi,则在首次启动时尝试获取网络信息时应用程序会崩溃或移动网络。
In addition to the permissions
.INTERNET
.ACCESS_NETWORK_STATE
.ACCESS_WIFI_STATE
mentioned in another answer, I also needed the following changes to the code:
Otherwise the app would crash when trying to get the network info on first startup, if I were not connected to either WiFi or Mobile Network.