I\'m trying to develop an android app that could erase others application cache data, I tried to browse through all blogs but none of them worked for me, I can able to clear
Cache is not just one thing. For each app there is a cache folder in the system data folders and one cache folder for every storage partition available (one in device's internal sd card and if there is an external sd card then there is one there too)
So to clear the cache in the system data folders you do this
Method method = pmClass.getDeclaredMethod("freeStorageAndNotify", new Class[] { Long.TYPE, Class.forName("android.content.pm.IPackageDataObserver") });
method.setAccessible(true);
method.invoke(con.getPackageManager(), Long.MAX_MALUE, null);
//null is for the IPackageDataObserver object that let's you know when the process is done and it is not necessary to provide.
Because you don't have access to the system folders to delete them by your self in a non rooted device so you politely ask Android to do it for you.
To clear the cache in the non-system data folders you do this
for(String storageVolumePath:storageVolumePaths) {
File androidDataFolder = new File((String) storageVolumePath + "/Android/data/");
if (androidDataFolder.exists()) {
File[] filesList = androidDataFolder.listFiles();
if (filesList != null) {
for (File file : filesList) {
if (file.isDirectory()) {
file = new File(file.getAbsolutePath() + "/cache/");
if(file.exists()) {
try {
deleteFile(file);
}catch (Exception e ){}
}
}
}
}
}
}
All in one toolbox DOES NOT clear cache from the system data folders in marshmellow because it is not possible without root access. It only uses the second technique and clears part of the total cache. To achieve that in API 23 and above without root access you need to be a system app because there is no way to request the android.permission.CLEAR_APP_CACHE permission using the Permission API