To provide a quick way for the user to clear out the cache, I am using the following function (based on this and this) attached to a Clear Cache button:
static void clearAppCache(Context context) {
try {
File dir = context.getCacheDir();
deleteDir(dir);
} catch (Exception e) {
// TODO: handle exception
}
}
private static boolean deleteDir(File dir) {
if (dir != null && dir.isDirectory()) {
String[] children = dir.list();
for (String aChildren : children) {
boolean success = deleteDir(new File(dir, aChildren));
if (!success) {
return false;
}
}
return dir.delete();
} else if (dir!= null && dir.isFile()) {
return dir.delete();
} else {
return false;
}
}
I'm also setting up my WebView with the same cache path, as follows:
WebSettings webSettings = mWebView.getSettings();
webSettings.setAppCacheEnabled(true);
String cachePath = getApplicationContext().getCacheDir().getAbsolutePath();
webSettings.setAppCachePath(cachePath);
My theory is that calling clearAppCache()
will also clear the WebView's cache because all it's doing is clearing out the same cache folder I've set for the WebView.
But since my WebView is now loading a page that uses a service worker, I'm finding that this doesn't seem to be clearing out the service worker cache. I've had reports from one user that, to really clear out the service worker stuff, they have to manually clear the content of the following folder (on their rooted device):
/data/data/com.example.myapp/app_webview/Cache/
Based on this post I have tried adding the following line to my clearAppCache()
function:
WebStorage.getInstance().deleteAllData();
But still this doesn't seem to have the effect of clearing the service worker cache.
Any ideas? Yes I know that the service worker cache can be cleared using javascript (see the above-linked post), but I want a way of doing this directly from Android.