I am trying to create a application that shows a WebView. I want it to display the cached version when there is no network. Else if there is a network available, it should load the WebView from the URL.
So far so good, except that it uses cached version all the time, even when there is network available. So I would like to ask if there is anything wrong with the code below. It seems that I am missing something.
I have tried both with the code below, and without it. I've found the following: no matter what I try, it seems that the app is always using the "cached" version. At this point i'm not even sure that it's truly using the cache, since I can only get it to load the website from URL again, when I have cleared App Data (not the cache).
Android version 6.0.1 API level 23
mWebView.getSettings().setAppCachePath(getApplicationContext().getCacheDir().getAbsolutePath() );
mWebView.getSettings().setAllowFileAccess( true );
mWebView.getSettings().setAppCacheEnabled( true );
mWebView.getSettings().setJavaScriptEnabled( true );
mWebView.getSettings().setCacheMode( WebSettings.LOAD_DEFAULT );
if ( !isNetworkAvailable() ) { // loading offline
mWebView.getSettings().setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);
}
mWebView.loadUrl("https://path.to.my/website/index.html");
Expected result: When phone has network, I expect it to fetch the website from the URL.
Actual result: When the installation is fresh, the website has been fetched from the url. Then after that, it will only use the cached version. (Or perhaps the verion stored in App Data. Not sure how that works.)
UPDATE:
I got it working, and it's now looking like this: (Unsure if this is the "best-practice" way to do it, though)
WebSettings webSettings = mWebView.getSettings();
webSettings.setAppCacheEnabled(true);
webSettings.setAllowFileAccess( true );
webSettings.setAppCachePath(getBaseContext().getCacheDir().getPath());
//webSettings.setJavaScriptEnabled( true );
if ( !isNetworkAvailable() ) { // loading offline
webSettings.setCacheMode( WebSettings.LOAD_CACHE_ONLY );
Toast.makeText(mContext, "DEBUG: No net",Toast.LENGTH_SHORT).show();
}
mWebView.loadUrl("https://path.to.my/website/index.html");