Search code examples
androidcachingandroid-webviewandroid-lifecycleandroid-ondestroy

Clear cache on webview when the app is killed


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?


Solution

  • You won't get any callbacks invoked if the system "decides" to kill your app being in background. If you, as a developer, can't rely on that, maybe you should rethink the approach to the problem?...

    What you know for sure is that when your app process is created the Application's onCreate() method is called. So why not clear the cache from within the method, i.e. not upon the app killing, but upon its launch?

    I followed this approach and created a service and cleared my cache at onTaskRemoved().

    Good approach, but, from my experience, in rare cases onTaskRemoved() isn't guaranteed to be called. I recommend to test the method call for different OS versions (and ideally for a range of devices). Also note that onTaskRemoved() is only called when a user removes your app from the recent task list.

    To sum up, if you use Application's onCreate() to clear the cache, the operation is guaranteed to be performed.