Home » Android » Android: Where should I save temporary files?

Android: Where should I save temporary files?

Posted by: admin June 15, 2020 Leave a comment

Questions:

My application allows users to create and modify files. I would like them to be able to send a file as an email attachment. So, I need to first create and write to a temporary file, which I then attach to the email. Unfortunately, based on the lone response to the below question, it seems there is no good way to know that the email application is done with the temporary file.

Android: problem sending email with attachment from my application

Because I can’t receive any notification that the email is done with the file, my rules for deleting temporary files are pretty bad. They are something like “check for temp files onPause and onCreate; delete anything over 5 minutes old”.

Because my rules are so ugly, I’m particularly concerned where I should write the files. I can not write them to the internal cache directory because their size can greatly exceed 1mb. Is it reasonable to create a folder devices’ sdcard: “/sdcard/myapp_tmp”? What is the common practice for this situation?

How to&Answers:

You can use Context’s getExternalCacheDir() method to get a File reference where you can store files on an SD card. Of course, you’ll have to do the usual checks to make sure the external storage is mounted and writable, as usual, but this is probably the best place to store that type of temporary file. One thing you might want to do is just set a maximum amount of space that you can use in the cache directory, and then, any time you need to write a new temporary file, if that file exceeds the maximum space, then start deleting the temp files, starting with the oldest, until there is sufficient space.

EDIT: Alternatively, maybe something like this would work:

if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
    File externalRoot = Environment.getExternalStorageDirectory();
    File tempDir = new File(externalRoot, ".myAppTemp");
}

Prepending the “.” should make the folder hidden, I’m fairly sure.