Is there any way to Clear all Cache files programmatically?

Viewed 829

I'm developing a program that delete the cache of all programs. This has been asked many times before but the solutions were either removed in newer versions of Android or didn't clear all caches or they needed to root the device.

I found a solution in Android docs that added in api 30 and should be launched using Activity#startActivityForResult(Intent, int) so that the user knows which app is requesting to clear cache. this action requires Manifest.permission.MANAGE_EXTERNAL_STORAGE in manifests.

I have this permission in my manifest and I using following code in my OnClick method:

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

But it doesn't work in my Android 11 device. Does anyone know code problem?

Thanks.

1 Answers

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

Check the documentation.

Use "startActivityForResult" instead of "startActivity":

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