Reference

onTrimMemory()

onTrimMemory() is an Android callback the system invokes on Application, Activity, and other ComponentCallbacks2 components to signal memory pressure. A level constant tells the app how urgently it should release memory, such as in-memory caches and bitmaps, to avoid being killed when the device runs low on RAM.

Android developmentAndroid

onTrimMemory()

Also known as: trim memory callback, memory pressure android

onTrimMemory() is an Android callback the system invokes on Application, Activity, and other ComponentCallbacks2 components to signal memory pressure. A level constant tells the app how urgently it should release memory, such as in-memory caches and bitmaps, to avoid being killed when the device runs low on RAM.

  • Delivered through the ComponentCallbacks2 interface on Application, Activity, and Service.
  • Higher level constants signal the process is closer to being killed by the low memory killer.
  • Common response is clearing bitmap/thumbnail and other rebuildable in-memory caches.

How the callback works

Components implementing ComponentCallbacks2 receive `onTrimMemory(int level)` from the framework. The `level` is one of several constants describing severity and process state. While the app is visible, TRIM_MEMORY_RUNNING_MODERATE, TRIM_MEMORY_RUNNING_LOW, and TRIM_MEMORY_RUNNING_CRITICAL indicate the device itself is low on memory and the app should trim non-essential allocations.

When the app moves to the background, the system delivers TRIM_MEMORY_UI_HIDDEN (UI no longer visible) and then increasingly severe TRIM_MEMORY_BACKGROUND, TRIM_MEMORY_MODERATE, and TRIM_MEMORY_COMPLETE levels indicating how close the process is to being killed by the low memory killer (LMK). Releasing memory at higher levels makes the process cheaper to keep alive.

What an app should release and the cleaner tie-in

On a trim signal the app should drop reclaimable caches: decoded bitmap / thumbnail caches, image-loader memory pools, and any large in-memory data that can be rebuilt. Libraries like Glide hook `onTrimMemory` to clear their memory cache automatically. Note that `onLowMemory()` is the older single-level equivalent for pre-API 14 behavior.

A storage and photo cleaner builds large in-memory thumbnail and scan-result caches while analyzing the library. Responding to onTrimMemory() lets it shrink those caches under pressure, keeping the foreground UI responsive and reducing the chance the scan process is killed mid-run. This is RAM management, distinct from freeing on-disk storage.

Related terms

Keep reading the reference.

Act on it

Guides and tools for this topic.