Android M反射方法freeStorageAndNotify异常

Android M reflection method freeStorageAndNotify exception

我正在使用反射方法 freeStorageAndNotify:

Method freeStorageAndNotify = null;
freeStorageAndNotify = service.packageManager.getClass().getMethod(
                "freeStorageAndNotify", long.class, IPackageDataObserver.class);
freeStorageAndNotify.invoke(PackageManager.class, maxCache + freeSpace, packageDataObserver);

这会导致 InvocationTargetException:

java.lang.SecurityException: Neither user 10199 nor current process has android.permission.CLEAR_APP_CACHE.

几点: - 我已经有 android.permission.CLEAR_APP_CACHE - 这只发生在 android "M" 版本中(从开发者网站刷新预览 sdk)

我知道这是一个 hack,google 没有为此带来一些官方 API, 但是有很多清理应用程序可以一键清理所有设备缓存,所以如果有人知道如何通过另一种解决方法绕过这个问题,我会很高兴看到。

非常感谢您的帮助

a bug 在 Android 5 上提出了关于任何应用如何可以清除具有常规权限的所有缓存文件,但不能清除一个包的缓存文件,除非具有签名级权限.

的详细信息

PackageManager has a deleteApplicationCacheFiles() to delete the cache from one package. This method is hidden from the SDK, and it requires DELETE_CACHE_FILES, a signature-level permission.

PackageManager also has a freeStorageAndNotify() method, to delete cache files from all packages. This method is hidden from the SDK, and it requires the CLEAR_APP_CACHE permission, which is merely flagged as "dangerous".

有人提议 DELETE_CACHE_FILES 应该放宽其级别, CLEAR_APP_CACHE 应该提高等级。

框架工程师回复

Note that freeStorageAndNotify's purpose is not to wipe out all cache files, but to free up X amount of space, for example by play store before it tries to download and install an app. So there are reasons to use it that work well with the system, but no reason for an app to use the method that just blindly erases all cache files for a single app (that is just there for the Settings app UI).

如果这确实不是应用程序错误,即您没有弄乱权限,它适用于 Marshmallow / 6 / api 23 而不是其他只能意味着它也成为签名级别的权限,例如 DELETE_CACHE_FILES

A signature|system permission, meaning that it can only be held by apps that are signed with the firmware's signing key or are installed on the system partition (e.g., by a rooted device user). As described in this answer.

考虑到他们的预期用途/他们的愿景,这是有道理的(应用程序没有理由使用盲目删除单个应用程序的所有缓存文件的方法)。它甚至可能由于该错误而受到限制。当 Android 6 的代码出来时我们会知道得更好(当前可用的是 5.1.1 - link to PackageManager's freeStorageAndNotify)。

参考这些页面:permissions by protection level and protection level definitions

android.permission.CLEAR_APP_CACHE

属于"signature|privileged"保护级别,只有同签名或特权应用(基本上是系统签名)才有此权限。

此外,您还应该检查一下 Behavior Changes 的一般情况。