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).
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…