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

HelloCW :

I use the following code to create some temp files, and wrapped tem as inputsteam to send to client side.

I understand that the temp files can be deleted automatically by android system when disk space low.

But I hope to I can delete the temp files by myself when I exit the App, how can I do? Thanks!

Code

File outputDir = context.getCacheDir(); // context being the Activity pointer
File outputFile = File.createTempFile("prefix", "extension", outputDir);
Jared Rummler :

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

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=452969&siteId=1