tags:

views:

80

answers:

1

I've got an app that is heavily based on remote images. They are usually displayed alongside some data in a ListView. A lot of these images are new, and a lot of the old ones will never be seen again.

I'm currently storing all of these images on the SD card in a custom cache directory (ala evancharlton's magnatune app).

I noticed that after about 10 days, the directory totals ~30MB. This is quite a bit more than I expected, and it leads me to believe that I need to come up with a good solution for cleaning out old files... and I just can't think of a great one. Maybe you can help. These are the ideas that I've had:

  1. Delete old files. When the app starts, start a background thread, and delete all files older than X days. This seems to pose a problem, though, in that, if the user actively uses the app, this could make the device sluggish if there are hundreds of files to delete.

  2. After creating the files on the SD card, call new File("/path/to/file").deleteOnExit(); This will cause all files to be deleted when the VM exits (I don't even know if this method works on Android). This is acceptable, because, even though the files need to be cached for the session, they don't need to be cached for the next session. It seems like this will also slow the device down if there are a lot of files to be deleted when the VM exits.

  3. Delete old files, up to a max number of files. Same as #1, but only delete N number of files at a time. I don't really like this idea, and if the user was very active, it may never be able to catch up and keep the cache directory clean.

That's about all I've got. Any suggestions would be appreciated.

+1  A: 
  1. Don't delete them all at once. Delete one every few seconds or something, and the user may not notice.
  2. The VM does not exit normally on Android, so deleteOnExit() will not be reliable.
  3. See #1 above.

You might also consider using AlarmManager to schedule deletion work for the wee hours of the morning. This has a side benefit of a capped CPU hit -- anything that runs truly in the background is capped to ~10% of CPU, so this work will not impact the user even if the user is actually using the device at that hour. You will need to use a WakeLock to keep the device awake while you are deleting things. One possibility is to use my WakefulIntentService for this, as it solves the problem of keeping the device awake and having it do the deletion work off the main application thread.

CommonsWare
I will use WakefulIntentService and the AlarmManager. Great idea - thanks!
synic