有没有办法以编程方式清除所有缓存文件?

Is there any way to Clear all Cache files programmatically?

我正在开发一个删除所有程序缓存的程序。这已经被问过很多次了,但是解决方案要么是 在 Android 的较新版本 中被删除,要么是没有清除 所有 缓存,或者他们需要 root 设备。

我在 Android docs 中找到了在 api 30 中添加的解决方案,应该使用 Activity#startActivityForResult(Intent, int) 启动,以便用户知道哪个应用程序请求清除缓存。 此操作需要 Manifest.permission.MANAGE_EXTERNAL_STORAGE 清单。

我的清单中有此权限,我在我的 OnClick 方法中使用了以下代码:

Intent clearCache = new Intent();
clearCache.setAction(ACTION_CLEAR_APP_CACHE);
startActivity(clearCache);

但它在我的 Android 11 设备上不起作用。有谁知道代码问题吗?

谢谢。

This intent should be launched using Activity#startActivityForResult(Intent, int) so that the user knows which app is requesting to clear cache.

检查documentation

使用“startActivityForResult”代替“startActivity”:

//Get cache dialog
int requestCode = 999;
Intent intent = new Intent(StorageManager.ACTION_CLEAR_APP_CACHE);
activity.startActivityForResult(intent, requestCode);