I have an android app that needs to be able to delete large directories quickly. I know that when an app has a lot of data, the OS is able to clear the data app instantly (from app settings). However, when I manually try to delete a directory with a background task, looping through the folders and deleting the files takes a long time (several minutes) to complete. How does the OS delete data so quickly, but when it is done in code, it takes such a long time? Is there a faster way to do it?
private boolean deleteDirectory(String dir) {
Log.d(TAG, "deleteDirectory");
// If dir is not separated from the end of the character to the file, the file is automatically added delimiter
if (!dir.endsWith(File.separator))
dir = dir + File.separator;
File dirFile = new File(dir);
// If dir corresponding file does not exist or is not a directory, then exit
if ((!dirFile.exists()) || (!dirFile.isDirectory())) {
return false;
}
boolean flag = true;
// delete all the files in the folder, including subdirectories
File[] files = dirFile.listFiles();
if (files != null) {
for (int i = 0; i < files.length; i++) {
final int count = i;
// delete subfolders
if (files[i].isFile()) {
try {
FileUtils.forceDelete(files[count]);
} catch (IOException e) {
Log.e(TAG, e.getLocalizedMessage(), e);
}
} else if (files[i].isDirectory()) {
flag = deleteDirectory(files[i]
.getAbsolutePath());
}
if (dir == path) {
Log.d(TAG, "delete dir: " + dirFile);
curPosi++;
publishProgress(curPosi);
}
}
}
if (!flag) {
return false;
}
// delete the current directory
if (dirFile.delete()) {
return true;
} else {
return false;
}
}