Design and Implement a Scalable Image Caching Mechanism in Android
Instruction: Explain the design and implementation process for a scalable image caching system in an Android application, considering different memory constraints and application states.
Updated
Official answer
Start with the image access pattern and a total memory budget. A decoded bitmap can be far larger than its compressed file. Decode near the display size, bound concurrent decoding and account for images currently displayed as well as those held in a cache. A fraction such as one eighth of the maximum heap is an example budget, not proof that the app cannot run out of memory.
Use one coordinated image-loading pipeline, commonly provided by a maintained library. For a custom design, key entries by content identity/version and relevant size/transformation options. Use a bounded memory LRU with bitmap byte accounting, a bounded disk cache with an eviction policy, and a network fallback. Deduplicate in-flight work for the same key. Disk caching saves repeated retrievals but still consumes storage, I/O and decoding memory.
Associate requests with their UI owner; cancel or detach obsolete requests and prevent a recycled view from displaying a prior item's result. Evicting a cache entry removes the cache's reference, but does not mean no view still uses the bitmap. Do not recycle a bitmap while another owner can draw it.
Do not clear an application-wide cache on every Activity onStop() or rely on onDestroy() to run. Use appropriate process/UI background signals and the library's lifecycle integration to release rebuildable resources. Android exposes ComponentCallbacks2.onTrimMemory(), not an ACTION_LOW_MEMORY broadcast. Older running-low trim levels and onLowMemory() are no longer delivered from API 34; the cache must stay bounded without waiting for them.
Test cold and warm loads, rapid scrolling, background/return and constrained-memory devices. Measure memory/disk hit rates separately, latency, peak memory and stale-image errors. Protect private cached content according to its sensitivity and account lifecycle.