Android的:所有的应用程序清除缓存?

问题描述:

在一个Android应用程序我提出的,我希望能够以编程方式清除所有设备上的应用程序的缓存。这已经被问过很多次: 清除应用程序缓存编程? http://*.com/questions/10262998/reflecting-methods-to-clear-android-app-cache 清除另一个应用程序缓存 大家都说这是不可能没有根。

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? http://*.com/questions/10262998/reflecting-methods-to-clear-android-app-cache Clear another applications cache and everyone says it's not possible without root.

然而,这显然不是这样。如果你看一下应用程序的应用程序缓存清理,历史记录清除器,1Tap清洁,易清洁的历史,和无数其他类似的应用程序在谷歌播放(所有这一切都不需要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?

感谢

下面是一个办法做到这一点,不需要 IPackageDataObserver.aidl

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"/>

这要求Android的足够清晰的缓存文件,以便有8GB可用。如果设置这个数字足够高,您应该实现你想要的(即Android将删除所有文件的缓存)。

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

这工作的方式是,Android的保持在所有应用程序的缓存目录中的所有文件的LRU(最近最少使用)名单。当你调用 freeStorage()它检查是否存储量(在这种情况下8GB)可用于缓存文件。如果不是,它开始于先删除最早的要删除的文件与应用程序的缓存目录中的文件。它继续删除文件,直到有不再任何要删除的文件,或已释放的存储您所请求的金额(在这种情况下8GB)。

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