Loading a single bitmap image into your android app is straightforward. However, on most cases you need to load many images at once into your UI view, this can damage your app responsiveness and downgrade your overall look and feel.
This post walks you through Google’s best practice for using a memory and disk caching to improve the responsiveness and fluidity of your UI when loading multiple images.
Memory Cache
The memory cache offers a fast access to images at the cost of reducing application memory. The LruCache class gives an API to store recently referenced objects in a strong referenced LinkedHashMap.
When choosing size for the LruCache, a few points need to be considered:
- How memory intensive our app is? If we need a lot of memory to run our app, we should consider reducing the cache size.
- How many images are we planning to show at once? and how many images do we need to store?
- Note that high density screens (xhdpi) need more memory to cache the same image than hdpi screens.
- What is the average image size, so we can predict how much memory space we need.
- How frequently will the images be accessed? we can consider using multiple LruCache instances.
Disk Cache
The memory cache is used to speed up our application and store frequently requested images. However, we can’t rely on images always being available in this cache. Our app can be interrupted by a phone call (or any other app) and while in the background it might be killed and the memory cache destroyed.
In these cases, a disk cache can be used to persists images, and help decrease loading time when the images are not available in the memory cache.
Fetching images from the disk is slower, and must be done on a separate background thread. Android disk cache implementation can be found in the DiskLruCache class.
Conclusion
Just like your app needs a smart and intuitive user interface, it also needs a good, well designed cache. A beautiful app which runs slow is as worse as an app with a bad UI.
Google’s sample code for using both memory cache and disk cache
Cheers