Reputation: 1869
I'm trying to implement a cache for my webView loaded in one of my activity in my app. But I can't load my webview when I turn off my current wifi network.
My webView:
progDialog = ProgressDialog.show(activity, "Loading", "Please wait...", true);
progDialog.setCancelable(false);
webView = (WebView) findViewById(R.id.my_web_view);
webView.getSettings().setJavaScriptEnabled(true);
webView.getSettings().setAppCacheEnabled(true);
webView.getSettings().setAppCachePath(getApplicationContext().getCacheDir().getAbsolutePath());
webView.setWebViewClient(new WebViewClient() {
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
progDialog.show();
if(isNetworkAvailable()){
view.getSettings().setCacheMode(WebSettings.LOAD_DEFAULT);
view.loadUrl(url);
}
else{
view.getSettings().setCacheMode(WebSettings.LOAD_CACHE_ONLY/*LOAD_CACHE_ELSE_NETWORK*/);
view.loadUrl(url);
}
return true;
}
@Override
public void onPageFinished(WebView view, final String url) {
progDialog.dismiss();
}
});
webView.loadUrl("http://www.google.com/");
I tried to use this method to be able to know if my webView content was saved in cache (don't sure if it's very correct, just a test):
private void isCacheFileCreated(){
String uri = "http://www.google.com/";
String hashCode = String.format("%08x", uri.hashCode());
File cacheFile = new File(new File(getCacheDir(), "webviewCache"), hashCode);
if (cacheFile.exists()){
// cache ok
} else {
// no cache
}
}
But when my network is off, file.exist() is always false.
My basic flow is: start my app > go to my activity with the webView and show the url content > turn off wifi > go back into my app > go back into the webview activity > and here I got an error message "Webpage not available".
Permissions in Manifest:
<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"/>
isNetworkAvailable() method:
private boolean isNetworkAvailable() {
ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
return activeNetworkInfo != null && activeNetworkInfo.isConnected();
}
Upvotes: 1
Views: 3054
Reputation: 6861
Google sets cache-control:no-cache
header, so its content is not cached by WebView. Try using a server where you can control the responses.
A few other notes:
AppCache is not a general web cache, your web app must explicitly use it (see the docs); thus turning it on would not help;
doing loadUrl
from inside shouldOverrideUrlLoading
is not necessary (and can sometimes lead to surprising results), you can just return false
instead;
not sure why you are assuming that web cache uses the particular scheme for naming files -- it's an implementation detail.
Upvotes: 4