Monthly Archives: March 2016

Timers in Android

One thing that’s always been curious to me is the lack of a simple timer class in Android. Instead you need to work around the lack in one of two ways. The easiest way is via a Handler. Its not hard to do, but its a little bit of busy work. The problem with this is that it’s only appropriate for very short timers or for things tied heavily to the UI. Its a non-exact timer and may be delayed indefinitely if the activity is paused or the phone goes idle. It won’t last beyond the Context that sets it at all. The other way is via an alarm. Alarms are persistent across Contexts and may be fairly exact. But they’re based on BroadcastReceivers, which can be tricky to work with- since the app may be started to process the alarm and call to the BroadcastReceiver, you have to code it carefully to get any data to persist until the broadcast occurs. In addition, Google keeps changing the AlarmManager API with respect to how exact timers are and correctly using it is a bit tricky.
Continue reading

Two level caching

This post builds off my post for disk caching. Sometimes you want a disk cache, to prevent unneeded network requests. Sometimes you want a memory cache, to put a cap on the amount of RAM you use. Sometimes you want both- you want a small fixed size working set in RAM, and a larger pool of objects saved to disk in case they’re needed. The solution is two level caching. The idea is that the memory cache is a subset of the disk cache, allowing you to page in from the disk cache to the memory cache as needed. Given you already have a disk cache (see previous post) the amount of extra code is pretty trivial. So I’ll skip the in depth discussion and just leave the solution here.
Continue reading

Disk caching on Android

Frequently when writing Android apps I’ll find the need for a cache. The classic case is with Bitmaps- adding all your bitmaps to a cache and grabbing them solely from the cache can solve a lot of OOM issues. And Google has written a great class, LRUCache, to easily enable memory caching. The problem is that memory caching frequently isn’t enough. If I have an app that needs to download lots of images from the net, I may need tens or hundreds of MB of images, and I don’t want to redownload them every time the app restarts or it falls out of a small memory cache. At the same time I don’t want to use up exponentially increasing amounts of disk space. The solution is to use a disk cache.
Continue reading