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);
I ended up here looking for a way to remove temp files that I was creating for camera intents, I actually used a combination of Sridhar's answer and the
cleanOldFiles
function from this answerI was creating a new image file using
createTempFile
and then adding that topublic static final HashSet<File> TEMP_FILES = new HashSet<>();
To iterate and remove from the set using the normal foreach loop was throwing a
java.util.ConcurrentModificationException
so I updated the loop using anIterator
more on iterators
Thought I'd post in case it helps someone else, thanks to Sridhar and ggrandes from the other post for the help.
The function removes files older than a given time value in seconds and is called like
First, keep in mind that "exit" for an Android app means something very different than it does for a desktop application. See this article for details, but the short answer is that, in general, you have no idea when the OS is actually going to close your app (even if it's not visible). In fact, there isn't an explicit guarantee that the OS will close it at all.
A few ideas can be found here (it's C#/Xamarin.Android but same exact idea for Java): How to detect application exit on android?
In addition to the stuff listed there, you could also try registering broadcast receivers for when the phone's shutting down.
Another (worse, in my opinion) way is to simply do this when the app becomes no longer visible (in
onStop
). As noted above, however, this isn't the same thing as the program actually closing (because you don't know when - or even if - the OS will actually close the app).It would be better if you can maintain a Set (Avoid Duplicates) for all files you create.
And iterate the file list and delete every file one by one.
And delete all by iterating.
call the
deleteOnExit()
method!Or
call the
delete()
method in theonStop()
of your activity.Edit:
It might be better if you called
delete()
inonDestroy()
to insure that your code works even if app is destroyed by system.Unfortunately it appears you have to delete these files one by one, by previously saving them in an array.
That being said, if you check Android Developers page on this issue it makes it as if you could delete the cached files "on a regular basis and also regularly delete other files you no longer need". However I don't think there is an explanation on how to do it.
Delete the files in
onDestroy
ifisChangingConfigurations()
isfalse
orisFinishing
istrue
. Example: