Stack Overflow archive
17 scoreaccepted

How to delete all temp files which created by createTempFile when exit an App in android?

score
17
question views
25.2K
license
CC BY-SA 3.0

Delete the files in onDestroy if isChangingConfigurations() is false or isFinishing is true. Example:

java
@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();
}

Originally posted on Stack Overflow. Public user contributions are licensed under Creative Commons Attribution-ShareAlike.