user1989237
user1989237

Reputation: 321

Android: Clear Cache of All Apps?

In an Android app I am making, I want to be able to programmatically clear the cache of all of the apps on the device. This has been asked many times before: Clearing app cache programmatically? Reflecting methods to clear Android app cache Clear another applications cache and everyone says it's not possible without root.

However, this is clearly not the case. If you look at the apps App Cache Cleaner, History Eraser, 1Tap Cleaner, Easy History Cleaner, and countless other similar apps in the Google Play (all of which don't require root) you will realize they can all do this. Therefore, it IS possible to do, but I just cannot find any public examples how to do this.

Does anyone know what all of those apps are doing?

Thanks

Upvotes: 26

Views: 27734

Answers (2)

David Wasser
David Wasser

Reputation: 95578

Here's a way to do it that doesn't require IPackageDataObserver.aidl:

PackageManager  pm = getPackageManager();
// Get all methods on the PackageManager
Method[] methods = pm.getClass().getDeclaredMethods();
for (Method m : methods) {
    if (m.getName().equals("freeStorage")) {
        // Found the method I want to use
        try {
            long desiredFreeStorage = 8 * 1024 * 1024 * 1024; // Request for 8GB of free space
            m.invoke(pm, desiredFreeStorage , null);
        } catch (Exception e) {
            // Method invocation failed. Could be a permission problem
        }
        break;
    }
}

You will need to have this in your manifest:

<uses-permission android:name="android.permission.CLEAR_APP_CACHE"/>

This requests that Android clear enough cache files so that there is 8GB free. If you set this number high enough you should achieve what you want (that Android will delete all of the files in the cache).

The way this works is that Android keeps an LRU (Least Recently Used) list of all the files in all application's cache directories. When you call freeStorage() it checks to see if the amount of storage (in this case 8GB) is available for cache files. If not, it starts to delete files from application's cache directories by deleting the oldest files first. It continues to delete files until either there are not longer any files to delete, or it has freed up the amount of storage you requested (in this case 8GB).

Upvotes: 35

Sunny
Sunny

Reputation: 14808

You can clear the data of all apps by using this (freeStorageAndNotify) method. You have to access this method using java reflection. You will need IPackageDataObserver.aidl for it. you also need to have permission in your manifest file for deleteing cache

Upvotes: 4

Related Questions