How to delete all temp files which created by createTempFile when exit an App in android?
Delete the files in onDestroy
if isChangingConfigurations()
is false
or isFinishing
is true
. Example:
@Override protected void onDestroy() {
super.onDestroy();
if(!isChangingConfigurations()) {
deleteTempFiles(getCacheDir());
}
}
private boolean deleteTempFiles(File file) {
if (file.isDirectory()) {
File[] files = file.listFiles();
if (files != null) {
for (File f : files) {
if (f.isDirectory()) {
deleteTempFiles(f);
} else {
f.delete();
}
}
}
}
return file.delete();
}
call the deleteOnExit()
method!
Or
call the delete()
method in the onStop()
of your activity.
Edit:
It might be better if you called delete()
in onDestroy()
to insure that your code works even if app is destroyed by system.