Android Performance

Android Code Memory Optimization Suggestions - OnTrimMemory

Word count: 687Reading time: 4 min
2015/07/20
loading

Android Memory Optimization Series:

  1. Android Code Memory Optimization Suggestions - Android (Official)
  2. Android Code Memory Optimization Suggestions - Java (Official)
  3. Android Code Memory Optimization Suggestions - Android Resources
  4. Android Code Memory Optimization Suggestions - OnTrimMemory

The onTrimMemory callback is an API introduced in Android 4.0. It provides hints to developers when system memory is low, allowing them to release resources proactively to avoid being killed by the OS. This ensures the app stays in the background longer and starts faster when the user returns.

This article uses a Q&A format to explain the usage and effectiveness of the onTrimMemory callback across various scenarios. If you want to build high-performance Android apps with great user experiences, don’t miss this.

0. What is the role of the onTrimMemory callback?

Introduced in Android 4.0, any class implementing the ComponentCallbacks2 interface can override this method. Its primary purpose is to guide applications in releasing memory under different conditions to avoid being killed, thereby improving user experience.

The system invokes this function with specific severity levels:

  • TRIM_MEMORY_UI_HIDDEN: Triggered when all UI components of the app are hidden (e.g., user pressed Home or Back). You should release UI-heavy resources here.

While the App is Running:

  • TRIM_MEMORY_RUNNING_MODERATE: Memory is getting low. The app is safe, but the system is starting to clear the LRU cache.
  • TRIM_MEMORY_RUNNING_LOW: Memory is quite low. Release unnecessary resources to maintain both system and app performance.
  • TRIM_MEMORY_RUNNING_CRITICAL: Memory is extreme. Most cached processes are dead. Release every non-essential resource to prevent the system from killing active services or the app itself.

While the App is Cached:

  • TRIM_MEMORY_BACKGROUND: Your app is at the “newest” end of the LRU list and unlikely to be killed. Release easy-to-rebuild resources to help the system.
  • TRIM_MEMORY_MODERATE: Your app is in the middle of the LRU list and is at risk if pressure continues.
  • TRIM_MEMORY_COMPLETE: Your app is at the “oldest” end of the LRU list and will be among the first to be killed. Release everything possible.

1. Which components can implement onTrimMemory?

  • Application.onTrimMemory()
  • Activity.onTrimMemory()
  • Fragment.onTrimMemory()
  • Service.onTrimMemory()
  • ContentProvider.onTrimMemory()

2. What resources should I release?

Decide during architecture which data must stay in RAM and which is UI-dependent. Common targets:

  • Caches: Image caches, file caches, etc. These are useful while the UI is visible but can be cleared when hidden.
  • Dynamically Added Views: Views that are rarely used or easy to recreate. For example, the Android Launcher releases resources for the widget picker in TRIM_MEMORY_MODERATE.

2.1 Example: Releasing Views (Launcher)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
// Launcher.java
@Override
public void onTrimMemory(int level) {
super.onTrimMemory(level);
if (level >= ComponentCallbacks2.TRIM_MEMORY_MODERATE) {
mAppsCustomizeTabHost.onTrimMemory();
}
}

// AppsCustomizeTabHost.java
public void onTrimMemory() {
mContent.setVisibility(GONE);
mPagedView.clearAllWidgetPages(); // Clears subviews, triggering bitmap deletion
}

2.2 Example: Clearing Caches (Contacts)

1
2
3
4
5
6
@Override
public void onTrimMemory(int level) {
if (level >= ComponentCallbacks2.TRIM_MEMORY_MODERATE) {
clear(); // Clears bitmap caches and pending requests
}
}

3. onTrimMemory vs. onStop

TRIM_MEMORY_UI_HIDDEN triggers only when all UI components are hidden. onStop() triggers whenever a single Activity is no longer visible (e.g., navigating to another Activity in the same app).

Best Practice: Use onStop() to release Activity-specific resources (network, receivers), but wait for TRIM_MEMORY_UI_HIDDEN to release shared UI assets. This prevents heavy reloading when navigating internal screens. Note that TRIM_MEMORY_UI_HIDDEN is called before onStop().

4. onTrimMemory vs. onLowMemory

onLowMemory is the older API. It’s roughly equivalent to TRIM_MEMORY_COMPLETE. Use it for API < 14 compatibility; otherwise, use onTrimMemory.

5. Why bother?

Even though the system kills processes based on the LRU list, it also targets high-memory consumers first to reclaim space quickly. Keeping your memory usage low increases the chance of a “Hot Start” (2-3x faster than a cold start), drastically improving the user’s perception of speed.

6. Typical Use Cases

  • Always-on Apps: Launcher, Security Center, Phone. These should release widget previews, image caches, and fragments upon exit.
  • Apps with Background Services: Music players, Downloaders. When the UI is hidden but the service continues, release all UI resources and caches immediately.

About Me && Blog

(Links and introduction)

CATALOG
  1. 1. 0. What is the role of the onTrimMemory callback?
    1. 1.1. While the App is Running:
    2. 1.2. While the App is Cached:
  2. 2. 1. Which components can implement onTrimMemory?
  3. 3. 2. What resources should I release?
    1. 3.1. 2.1 Example: Releasing Views (Launcher)
    2. 3.2. 2.2 Example: Clearing Caches (Contacts)
  4. 4. 3. onTrimMemory vs. onStop
  5. 5. 4. onTrimMemory vs. onLowMemory
  6. 6. 5. Why bother?
  7. 7. 6. Typical Use Cases
  • About Me && Blog