26

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

Community
  • 1
  • 1
user1989237
  • 321
  • 1
  • 3
  • 9
  • 1
    Have you emailed the developers? One of them might be willing to divulge their code. – Stealth Rabbi Jan 24 '13 at 17:27
  • 1
    The questions you linked to are for clearing the cache of *individual apps*. That is not possible without holding a permission that is only available for apps that are installed on the system partition (e.g., by rooted users) or are signed with the firmware signing key. The apps you cite offer clearing *all apps' caches*, not those of individual apps. For reasons that remain unfathomable, it *is* possible to wipe all apps' caches without any permission, though it is not possible through the Android SDK. – CommonsWare Jan 24 '13 at 17:47
  • @CommonsWare Actually in order to clear out cache files you **do** need permission "android.permission.CLEAR_APP_CACHE" – David Wasser Jan 24 '13 at 19:14
  • @DavidWasser: Ah, sorry, I mis-remembered. However, `CLEAR_APP_CACHE` is one that you can hold, whereas the delete-only-one-app's-cache requires a `signature|system` permission. – CommonsWare Jan 24 '13 at 19:27
  • 1
    @CommonsWare No problem. We all mis-remember on occasion ;-) I won't hold it against you – David Wasser Jan 24 '13 at 19:28
  • @CommonsWare Any Idea what is the issue on Android Oreo. I am using freeStorageAndNotify in which I get the call back to IPackageDataObserver.onRemoveCompleted(String packageName, boolean succeeded) but the succeeded is false. Any leads? – Vinayak Bevinakatti Sep 04 '18 at 18:36
  • @VinayakBevinakatti: I avoid using hidden methods wherever possible, and so I have not played with that one in years. Note that Android 9.0 is starting to crack down on access to such hidden methods. – CommonsWare Sep 04 '18 at 20:48
  • @CommonsWare Thanks for the quick reply. Yes, you're right. But it is the only way as per my knowledge to clear all apps cache. Please suggest if you know any other safe way that is possible. I am trying this on a app which is reside in /system/priv-apps/ which have root permissions. – Vinayak Bevinakatti Sep 04 '18 at 21:59

2 Answers2

35

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).

David Wasser
  • 93,459
  • 16
  • 209
  • 274
  • So if I wanted to make sure it cleared everything, would there be any problem with just setting it to something ridiculous like 256GB? Because some devices have 16GB or 32GB of internal storage – user1989237 Jan 24 '13 at 20:06
  • Yes, that should work (and is probably exactly what these "cache cleaner" apps are doing) – David Wasser Jan 24 '13 at 20:20
  • Just tested this code, and it isn't working. The method "freeStorage" is found, and is called successfully with method.invoke (no exceptions are thrown). However, the cache isn't being cleared for any apps. I verified in the Application Info window and also with Root Explorer navigating to the /data/data/packagename/cache directory that all of the data is still there – user1989237 Jan 24 '13 at 20:27
  • 7
    Ok, I got it working by using freeStorageAndNotify instead of freeStorage. I tried setting the IPackageDataObserver to null, and it worked so that's actually an optional parameter even though it doesn't say it in the method description. EDIT: And for anyone trying to clear all of the caches, change desiredFreeStorage to Long.MAX_VALUE – user1989237 Jan 24 '13 at 20:56
  • 1
    Glad you were able to get it to work, and thanks for the feedback. I'm curious as to why `freeStorage()` didn't work. I'll need to spend some more time on that one. – David Wasser Jan 24 '13 at 21:44
  • @DavidWasser Can you guide me regarding a cache topic? I want to calculate sum of cache size used by all apps installed in device. –  Apr 24 '13 at 07:29
  • 2
    Also, the code that you've got will only clear enough cached files to free up 8GB. If you already have 8GB of available storage this code won't do anything. If you really want to delete all cached files, set `desiredFreeStorage = Long.MAX_VALUE` – David Wasser Jun 26 '13 at 14:56
  • @David sir ,Above code is working well for clear cache of all installed apps on device. But anyhow can we clear data of installed apps on device? – Brijesh Patel May 26 '14 at 05:54
  • @BrijeshPatel no, you cannot do that (as far as I know). Sorry. – David Wasser May 26 '14 at 07:06
  • Isn't there way to do it without reflection? Also, does it work on Lollipop? what kind of storage does it handle? the internal and/or external storage? And what about SD-cards ? I assume there is a cache there too, right? – android developer Nov 26 '14 at 08:11
  • 1
    @BrijeshPatel You can do it with ROOT, or by using a PC. if you wish, I can tell you how. I did it on my app: https://play.google.com/store/apps/details?id=com.lb.app_manager&ah=3x5LB6cyGlgL4s3IsCY8rKpshSk – android developer Nov 26 '14 at 08:16
  • @androiddeveloper OP asked specifically for a solution on a non-rooted device. Stackoverflow is full of solutions for rooted devices. Also, OP specifically asked for a "programmatic" solution. Suggesting that he can connect the device to his PC to do it isn't helpful, nor does it solve his problem. – David Wasser Nov 26 '14 at 09:03
  • @androiddeveloper No, there is no way to do this without using reflection. The necessary methods are not publicly available. This clears the cache only, and as far as I know, the caches are located on the internal memory. But this is clearly a device-specific thing. – David Wasser Nov 26 '14 at 09:04
  • @DavidWasser About root, ok. About reflection, too bad. So it's unknown how the method will work on various devices, as it could handle the free space of just the internal storage, and it could also, in addition, handle the external storage. There is also cache on the external storage : http://developer.android.com/reference/android/content/Context.html#getExternalCacheDir() , and there is also one for additional types of external storage, which is called "getExternalCacheDirs" . in the app-info screen, if you choose to clear the cache, it also clears the one of the external storage. – android developer Nov 26 '14 at 09:14
  • @androiddeveloper You don't have any control over this. You tell the system that you want "X" bytes of free space in the cache, and it should please delete some stuff to make space available for you. You have absolutely no control over where it does this or how it does this. – David Wasser Nov 26 '14 at 09:33
  • @DavidWasser I understand. So it's a bit useless I think... Does the OS also clean the cache automatically? I remember I've read that it should, yet the developers should also manage cache files inside the app itself. – android developer Nov 26 '14 at 14:09
  • This is not working in JellyBean Version. Can anyone give a solution for that. – Arunraj Jeyaraj Jun 24 '15 at 07:58
  • I run in my android studio your code . it throw exception: java.lang.IllegalArgumentException: Wrong number of arguments; expected 3, got 2 @David Wasser. –  Apr 26 '16 at 11:14
  • @Omr You should open a new question and post your code. This is the wrong place to discuss your problem. – David Wasser Apr 26 '16 at 11:54
  • Error: `java.lang.IllegalArgumentException: Wrong number of arguments; expected 3, got 2` on line `m.invoke()`. – Kaushal28 Dec 30 '17 at 11:02
  • @Kaushal28 See https://stackoverflow.com/a/36937517/769265 for a solution to the `IllehalArgumentException`. But sadly, this method no longer works as of Android 6 :-( – David Wasser Dec 31 '17 at 08:24
  • Yes I've implemented that but due to security exception it's not working. Any alternatives? – Kaushal28 Jan 01 '18 at 06:38
  • @DavidWasser Have you tried this on Android Oreo? Its not working for me. I am using freeStorageAndNotify in which I get the call back to onRemoveCompleted(String packageName, boolean succeeded) but the succeeded is false. Any leads? – Vinayak Bevinakatti Sep 04 '18 at 18:14
4

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

Community
  • 1
  • 1
Sunny
  • 14,522
  • 15
  • 84
  • 129
  • Code HERE: http://stackoverflow.com/questions/17313721/how-to-delete-other-applications-cache-from-our-android-app – Zohar Sep 06 '16 at 08:39