I am using WebViews in an Android app, and I need to prevent the WebViews from caching.
Unfortunately it seems like this seemingly simple goal is nearly impossible to achieve. The solution I have resorted to use is to execute webview.clearCache(true) in the onPageFinished event so that the cache is cleared each time a page is loaded. There are some issues...
I have noticed that as the cache grows it becomes very time consuming for the clearCache method to execute. Sometimes if you execute clearCache and then switch to a different Activity that contains different webview, that webview will not load for a few seconds because it is still waiting on the previous clearCache operation to finish.
What's worse is that execution time of subsequent calls to clearCache does not seem to decrease after the cache has been already cleared. If the call to clearCache takes 3 seconds to complete and then I immediately call clearCache a second time, then I would expect the second call to clearCache to complete almost immediately. But that is not what I'm experiencing; I'm experiencing that the second call to clearCache still take approximately 3 seconds.
Has anyone else experienced this? Is there any way to improve performance? Waiting 2-3 seconds for a webview to load (from the local filesystem) is horrible.
EDIT:
Here is my best alternative to actually clearing the cache. It more or less works but it's sort of flaky and I'm not 100% happy with it (written in Mono c#):
public class NoCacheWebClient : WebViewClient
{
string previous;
public override void OnPageStarted(WebView view, string url, Android.Graphics.Bitmap favicon)
{
base.OnPageStarted(view, url, favicon);
if (!string.Equals(previous, url))
{
previous = url;
view.Reload(); //re-load once to ignore cache
}
else
{
previous = null;
}
}
}
As you are going to the next activity finish the previous activity. So that you can free all memory occupied by that activity. Hope this helps.
1) Try using setAppCacheEnabled and setAppCacheMaxSize to limit the cache size to very little , lower cache size will result in faster cleanup.
Ex:
wv.getSettings().setAppCacheMaxSize(1);
OR
2) If you don't need the cached data then simply set setCacheMode(WebSettings.LOAD_NO_CACHE); , which means "Don't use the cache, load from the network", even though data is cached.
In-short, simply ignore the cached data, android will take care of it.
OR
3) you can also try the below code for no-caching,
Note: this is only available for Android API 8+
OR
4) Clear the cache every-time whenever page load finishes. Something like this in the
WebViewClient
.OR
5) You can try deleting whole cached database at once.
This might give a bit faster result, hope so.