Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

android

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);
like image 635
HelloCW Avatar asked Feb 26 '17 03:02

HelloCW


People also ask

Can I delete all items in temp folder?

Type temp and press Enter (or click OK) to open up the folder location and see your temp files. Hold Ctrl and click individual items to select them for cleanup. If you want to delete everything in your temp folder, press Ctrl + A to select all the items.


1 Answers

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();
}
like image 89
Jared Rummler Avatar answered Sep 21 '22 19:09

Jared Rummler