Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
955 views
in Technique[技术] by (71.8m points)

caching - 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

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share

2.1m questions

2.1m answers

62 comments

56.6k users

...