How do you handle Bitmaps in Android to prevent memory leaks?

Instruction: Discuss strategies for managing large Bitmaps in Android applications to avoid memory issues.

Context: Assess image decoding size, bounded concurrency, byte-aware caching, lifecycle ownership and safe release of bitmap references. Distinguish a retained-reference leak from a temporary allocation peak.

Updated

Official answer

A large bitmap can exhaust memory without a leak. A leak means an object remains reachable beyond its useful lifetime; oversized decoding and too many simultaneous images can cause a high legitimate allocation peak. Diagnose which problem exists before choosing a fix.

  • Decode for the display size. Inspect image dimensions before allocating pixels and downsample to the required target size. Compressed file size does not equal decoded memory. Perform expensive loading and decoding off the main thread, and bound concurrent requests.
  • Use a lifecycle-aware image loader where practical. Cancel or replace requests when a view is rebound or destroyed, and avoid retaining activities or views in long-lived callbacks and caches. Clear references according to ownership.
  • Bound the cache by memory. An LruCache counts entries by default. Override sizeOf with a consistent bitmap-size unit if the budget is in bytes or KiB. Include displayed images, in-flight decodes and other allocations when choosing the budget; limiting one cache does not cap the whole process.
  • Do not recycle shared pixels prematurely. Bitmap.recycle() releases the bitmap's pixel data and makes it unusable; it does not merely mark the object for garbage collection. Calling it automatically from onDestroy or cache eviction is unsafe if another view, cache or operation still uses that bitmap. Legacy code that recycles manually needs explicit ownership tracking. On modern Android, prefer correct lifecycle handling and releasing references over blanket recycling.

Profile repeated scrolling, rotation, navigation away and return, and multiple large loads on representative devices. Check retained activity instances, bitmap allocations and peak memory. A cache hit-rate improvement is useful only if it does not create unacceptable retention or memory pressure.

Sources

Android bitmap memory and recycling; bitmap cache sizing; LruCache units.

Related Questions