StuStirling
StuStirling

Reputation: 16191

Handling Internal Cache

I am saving MapTiles to my internal cache which I retrieve using getCacheDir(). I have a few questions regarding the handling of the cache size.

  1. How should I go about setting a maximum size for my cache directory before I start handling the deletion of files? With the newer devices a large cache isn't so much of a problem as there is quite a bit of space (not limitless but a fair amount), however the older devices have quite small internal memory and therefore cache sizes are going to be more important...
  2. At the moment, I store a tile's use count and last used timestamp so I know which tiles I can delete and which not to delete. This way I can see which are used and which aren't, allowing me to remove the less used tiles. What happens when the Android OS decides it needs space and delete my cache? Is there an Intent I can listen for that tells me which files in my application's cache were deleted?

Upvotes: 0

Views: 253

Answers (2)

Flo
Flo

Reputation: 1499

Regarding 1) In my applications I often use disc based image caches. I have always used a fixed cache size, which has worked fine so far. I don't know about your size requirements, but you could determine the total available disc size and calculate some ratio of that (see: Getting all the total and available space on Android). You probably want to set some max upper limit though, users won't be happy if your app eats up all their free disc space ;)

Regarding 2) Android won't secretly delete your persisted files. The only thing that might happen is that the user decides to delete application data or all cached files of your app. In such a case, all data will be gone, and you will have to re-initialize your cache.

Upvotes: 0

Budius
Budius

Reputation: 39836

  1. for how to handle the size, I guess the best approach is to check how much are you using:

    • here it shows how to get free space Get free space on internal memory
    • the class shown on this link StatFs can also tell you what is the total size
    • So based on those values you can set to take a max of 2% of the total memory for as long as you have at least 10% free (for example)
  2. no, there's really nothing you can do about it. Your software should be able to check for deleted tiles and re-download them if necessary.

and as an alternative to your apprach, I suggest you to use a LruDiskCache from JakeWharton (https://github.com/JakeWharton/DiskLruCache)

I believe that re-inventing the wheel is bad and unnecessary, so if there's a library that is already doing all of most of the heavy lift, why will I bother code it again?

Upvotes: 1

Related Questions