I am implementing an app to clean cache of installed applications,And what I have tried is following :
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();
}
And I also have declared following permissions in manifest file : uses-permission android:name="android.permission.GET_PACKAGE_SIZE" uses-permission android:name="android.permission.CLEAR_APP_CACHE"
But it's not clearing cache. What's the reason ?