在Android中清除应用缓存

时间:2017-03-22 07:14:02

标签: java android file package-managers

我正在实现一个应用程序来清理已安装应用程序的缓存,我尝试过的是:

 public static void freeAllAppsCache(final Handler handler,Context oContext)
  {
    File externalDir = oContext.getApplicationContext().getExternalCacheDir();
    if (externalDir == null) {
        return;
    }
    PackageManager pm = oContext.getApplicationContext().getPackageManager();
    List<ApplicationInfo> installedPackages = pm.getInstalledApplications(PackageManager.GET_GIDS);
    for (ApplicationInfo info : installedPackages)
    {
        String externalCacheDir = externalDir.getAbsolutePath().replace(oContext.getApplicationContext().getPackageName(), info.packageName);
        File externalCache = new File(externalCacheDir);
        if (externalCache.exists() && externalCache.isDirectory())
        {
            deleteFile(externalCache);
        }
    }

    try {
        Method freeStorageAndNotify = pm.getClass()
                .getMethod("freeStorageAndNotify", long.class, IPackageDataObserver.class);
        long freeStorageSize = Long.MAX_VALUE;

        freeStorageAndNotify.invoke(pm, freeStorageSize, new IPackageDataObserver.Stub() {
            @Override
            public void onRemoveCompleted(String packageName, boolean succeeded) throws RemoteException {
                Message msg = handler.obtainMessage(MainActivity.MSG_SYS_CACHE_CLEAN_FINISH);
                msg.sendToTarget();
            }
        });

    } catch (NoSuchMethodException e) {
        e.printStackTrace();
    } catch (IllegalAccessException e) {
        e.printStackTrace();
    } catch (InvocationTargetException e) {
        e.printStackTrace();
    }

}

public static boolean deleteFile(File file) {
    if (file !=null && file.isDirectory()) {
        String[] children = file.list();
        if (children != null)
        {
            for (String name : children) {
                boolean suc = deleteFile(new File(file, name));
                if (!suc) {
                    return false;
                }
            }
    }
    }
    return file.delete();
}

我还在清单文件中声明了以下权限:       uses-permission android:name =&#34; android.permission.GET_PACKAGE_SIZE&#34;       uses-permission android:name =&#34; android.permission.CLEAR_APP_CACHE&#34;

但它没有清除缓存。原因是什么?

0 个答案:

没有答案