I have seen other answers on stackoverflow but none of them helped me solve my issue.
I have an application with webview in a activity, I want to clear cache when the application is killed.
Below is the code I'm using to delete the cache-
public static void deleteCache(Context context) {
try {
File dir = context.getCacheDir();
deleteDir(dir);
} catch (Exception e) {}
}
public static boolean deleteDir(File dir) {
if (dir != null && dir.isDirectory()) {
String[] children = dir.list();
for (int i = 0; i < children.length; i++) {
boolean success = deleteDir(new File(dir, children[i]));
if (!success) {
return false;
}
}
return dir.delete();
} else if(dir!= null && dir.isFile()) {
return dir.delete();
} else {
return false;
}
I want to clear cache when application is killed or just before the app is going to be killed, where do I call deleteCache(this)
?
I tried putting it in OnDestroy()
method of the activity , but it clears the cache when I press back button on the activity which is not my requirement.
So I added
@Override
public void onBackPressed() {
moveTaskToBack(true);
}
So my activity doesn't call onDestroy() at all when I press back button nor I kill the application.
Where do I need to clear the cache on the lifecycle methods ? and Where can I trigger an event to javascript function just before my app is killed?