DEV Community

Cover image for Under the Ceiling: Measuring Your Real Memory Headroom on Android 17
Android Expert
Android Expert

Posted on Originally published at Medium

Under the Ceiling: Measuring Your Real Memory Headroom on Android 17

Your app may now be killed earlier on low-RAM devices. Here is how to measure the headroom you actually have, and how to spend it on purpose.

For about a decade, “how much memory can my app use?” had a comfortable answer: call ActivityManager.getMemoryClass(), shrink your caches to fit, and move on. Android 17 (API 37) changes the question. The platform now applies app memory limits that scale with the device's total RAM, and a process that crosses its limit is terminated, regardless of what the Java heap says.

Google describes the initial limits as conservative, aimed at extreme leaks and outliers rather than ordinary apps. That is reassuring right up until your photo viewer, running on a 3 GB device after twenty minutes of browsing, turns out to be an outlier.

This post covers:

  1. What changed, and why the heap number you have been trusting is only part of the picture.
  2. How to measure real headroom in code and with adb.
  3. How to detect a limiter kill in production.
  4. onTrimMemory, done honestly.
  5. Bitmap budgeting.
  6. A per-screen memory budget you can enforce in debug builds.
  7. The failure modes that bite in practice.

1. Two ceilings, one process

The old ceiling is the Java heap cap. getMemoryClass() reports the per-app heap class in MiB, and Runtime.maxMemory() reports the ceiling ART will actually enforce, which rises above the heap class when android:largeHeap is set. Exceed it and you get an OutOfMemoryError you can at least log.

The new ceiling is different in kind. Per Android’s behavior-change notes, limits are derived from the device’s total RAM, and the platform exposes separate limits for visible and non-visible processes. An app killed by the limiter shows up in ApplicationExitInfo as REASON_OTHER with a description containing MemoryLimiter:AnonSwap. That name hints that anonymous memory and swapped-out pages are what gets counted, which would include native allocations the Java heap never sees. Whether graphics buffers count depends on how they are mapped, so measure them rather than assuming either way. Treat all of this as an inference from the name, not a documented guarantee.

memory-ceiling-layers

Two consequences follow immediately:

  • largeHeap does not buy you the second ceiling. It raises the Java slice and nothing else. It can even make things worse by letting the heap grow into territory the limiter cares about.
  • The exact numbers are not published. Do not hardcode “my limit is X MB”. Read it from the device you are testing on, as shown next.

2. getMemoryClass() versus what actually kills you

Start by seeing the numbers side by side. The following probe collects what the old APIs report and what the process is actually holding.

import android.app.ActivityManager
import android.content.Context
import android.os.Debug
import java.io.File

data class MemorySnapshot(
    val javaHeapLimitMib: Int,        // getMemoryClass(): Java heap class, advisory
    val javaHeapUsedMib: Long,
    val nativeHeapMib: Long,
    val graphicsMib: Long,            // from Debug.MemoryInfo, platform-reported
    val rssAnonMib: Long,             // anonymous resident pages
    val swapMib: Long,                // pages pushed out to zram
    val systemLowMemory: Boolean,
) {
    /** Closest user-space approximation of "anon + swap" that we can read cheaply. */
    val anonPlusSwapMib: Long get() = rssAnonMib + swapMib
}

/** Does binder and procfs I/O. Call from a background dispatcher, never from the main thread. */
class MemoryProbe(context: Context) {
    private val am = context.getSystemService(ActivityManager::class.java)

    fun snapshot(): MemorySnapshot {
        val runtime = Runtime.getRuntime()
        val debugInfo = Debug.MemoryInfo().also { Debug.getMemoryInfo(it) }
        val sys = ActivityManager.MemoryInfo().also { am.getMemoryInfo(it) }

        return MemorySnapshot(
            javaHeapLimitMib = am.memoryClass,
            javaHeapUsedMib = (runtime.totalMemory() - runtime.freeMemory()).toMib(),
            nativeHeapMib = Debug.getNativeHeapAllocatedSize().toMib(),
            graphicsMib = debugInfo.getMemoryStat("summary.graphics")?.toLongOrNull()?.kbToMib() ?: 0L,
            rssAnonMib = readProcStatusKb("RssAnon").kbToMib(),
            swapMib = readProcStatusKb("VmSwap").kbToMib(),
            systemLowMemory = sys.lowMemory,
        )
    }

    private fun readProcStatusKb(key: String): Long = runCatching {
        File("/proc/self/status").useLines { lines ->
            lines.firstOrNull { it.startsWith("$key:") }
                ?.substringAfter(':')
                ?.trim()
                ?.substringBefore(' ')
                ?.toLong()
        } ?: 0L
    }.getOrDefault(0L)

    private fun Long.toMib() = this / (1024 * 1024)
    private fun Long.kbToMib() = this / 1024
}
Enter fullscreen mode Exit fullscreen mode

Run it on a real device mid-session and look at the gap between javaHeapUsedMib and anonPlusSwapMib. Apps heavy on images, video, WebView or ML runtimes often show a native-plus-graphics total far larger than the Java heap, though the ratio depends entirely on your workload, so profile your own app. That gap is the part getMemoryClass() never warned you about.

Reading the actual limit

Android 17 ships adb tooling to inspect and adjust the limiter on devices that enforce it:

# Show the limits applied to visible and non-visible processes
adb shell am memory-limiter status

# Pin a specific process to a manual limit (use the units shown by status)
adb shell am memory-limiter manual <pid> <limit>

# Exempt a UID, or everything, while you separate leaks from limit effects
adb shell am memory-limiter ignore <uid>|none|all
Enter fullscreen mode Exit fullscreen mode

The commands have no effect on devices that do not impose limits, which is itself a testing trap (see section 7).

headroom-measurement-flow

Here is the “subtract” step as code. Feed it the limit you read from status on your weakest test device, then log the lowest headroom per route.

import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.flowOn
import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.delay
import kotlin.time.Duration
import kotlin.time.Duration.Companion.seconds

data class Headroom(val usedMib: Long, val limitMib: Long) {
    val freeMib get() = limitMib - usedMib
    val percentFree get() = if (limitMib == 0L) 0 else (freeMib * 100 / limitMib).toInt()
}

fun MemoryProbe.headroomUpdates(
    limitMib: Long,
    every: Duration = 2.seconds,
): Flow<Headroom> = flow {
    while (true) {
        emit(Headroom(usedMib = snapshot().anonPlusSwapMib, limitMib = limitMib))
        delay(every)
    }
}.flowOn(Dispatchers.IO) // snapshot() does binder and file I/O; keep it off the main thread
Enter fullscreen mode Exit fullscreen mode

The flowOn(Dispatchers.IO) matters: snapshot() makes a binder call and reads procfs, so collecting from a UI scope without it would do that work on the main thread every two seconds. Collect it from a debug-only overlay or a trace marker. The aim is a number per screen, such as "Photo viewer bottoms out at 14% free on the 3 GB device", not a one-off reading.

Caveat: RssAnon + VmSwap is an approximation of what the limiter counts, not a copy of its accounting. Use it to find trends and regressions, and let am memory-limiter status plus real kill reports be the ground truth.

3. Catching a limiter kill in production

A killed process cannot log its own death, but the next launch can read the obituary. ApplicationExitInfo (API 30+) records recent exits.

import android.app.ActivityManager
import android.app.ApplicationExitInfo
import android.content.Context
import android.os.Build

sealed interface PriorExit {
    data class LimiterKill(val timestamp: Long, val description: String) : PriorExit
    data class SystemPressure(val timestamp: Long) : PriorExit
    data class JavaOom(val timestamp: Long) : PriorExit
}

fun readMemoryRelatedExits(context: Context, sinceMillis: Long): List<PriorExit> {
    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.R) return emptyList()
    val am = context.getSystemService(ActivityManager::class.java)

    return am.getHistoricalProcessExitReasons(/* packageName = */ null, /* pid = */ 0, /* max = */ 10)
        .asSequence()
        .filter { it.timestamp > sinceMillis }
        .mapNotNull { info ->
            val description = info.description.orEmpty()
            when {
                info.reason == ApplicationExitInfo.REASON_OTHER &&
                    "MemoryLimiter:AnonSwap" in description ->
                    PriorExit.LimiterKill(info.timestamp, description)

                info.reason == ApplicationExitInfo.REASON_LOW_MEMORY ->
                    PriorExit.SystemPressure(info.timestamp)

                info.reason == ApplicationExitInfo.REASON_CRASH &&
                    "OutOfMemoryError" in description ->
                    PriorExit.JavaOom(info.timestamp)

                else -> null
            }
        }
        .toList()
}
Enter fullscreen mode Exit fullscreen mode

Persist the last-seen timestamp (DataStore is fine) so you report each death once, and attach the screen you were on when the process went away. Without that breadcrumb, a limiter kill is just a mystery disappearance.

exit-diagnosis-tree

Why three buckets? Because the fixes differ. A limiter kill means your process is too fat. A REASON_LOW_MEMORY kill often means your background footprint is too fat while the user was in another app. A Java OOM is the classic heap problem. Lumping them together hides which lever to pull.

For the investigation step, Android 17 also extends trigger-based profiling with TRIGGER_TYPE_ANOMALY, which can collect a heap dump when the memory limit is hit. Check the ProfilingManager documentation for the registration details, since this is a newer API surface.

4. onTrimMemory, without wishful thinking

onTrimMemory is the system saying "I am under pressure, give something back". Register it once at the application level and route it to anything that holds rebuildable memory.

import android.app.Application
import android.content.ComponentCallbacks2

interface Trimmable {
    fun trim(level: Int)
}

class TrimRegistry {
    // WeakHashMap is not thread-safe, so every access goes through this lock.
    private val lock = Any()
    private val targets = java.util.Collections.newSetFromMap(
        java.util.WeakHashMap<Trimmable, Boolean>()
    )

    fun register(t: Trimmable) = synchronized(lock) { targets += t }

    fun dispatch(level: Int) {
        val snapshot = synchronized(lock) { targets.toList() }
        snapshot.forEach { it.trim(level) } // run callbacks outside the lock
    }
}

class App : Application() {
    val trimRegistry = TrimRegistry()

    override fun onTrimMemory(level: Int) {
        super.onTrimMemory(level)
        trimRegistry.dispatch(level)
    }
}

class ImageMemoryCache(private val cache: BitmapLruCache) : Trimmable {
    override fun trim(level: Int) = when (level) {
        ComponentCallbacks2.TRIM_MEMORY_RUNNING_CRITICAL -> cache.evictAll()
        ComponentCallbacks2.TRIM_MEMORY_RUNNING_LOW      -> cache.evictToFraction(0.25f)
        ComponentCallbacks2.TRIM_MEMORY_RUNNING_MODERATE -> cache.evictToFraction(0.5f)
        ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN        -> cache.evictAll()
        else -> Unit
    }
}
Enter fullscreen mode Exit fullscreen mode

Matching levels exactly, rather than with a >= ladder, is deliberate. TRIM_MEMORY_UI_HIDDEN (20) is numerically above RUNNING_CRITICAL (15) even though it is far less urgent: it belongs to a different family and means "your UI is gone", not "the system is hurting". A threshold comparison would quietly treat a hidden UI as a critical emergency. The two families also fire in different situations: RUNNING_* arrives while your UI is still visible and the system is tight, while UI_HIDDEN arrives when you move to the background. Do not assume UI_HIDDEN has already run when a RUNNING_* level arrives.

ontrimmemory-ladder

What onTrimMemory will not do for you

  • It is a hint about system pressure, not a countdown to your own cap. Do not assume you will be warned before a per-process limiter terminates you. Design as if you will not be.
  • The background-tier constants are deprecated. TRIM_MEMORY_BACKGROUND, MODERATE and COMPLETE were deprecated in API 34. Build on UI_HIDDEN and the RUNNING_* levels.
  • UI_HIDDEN is your best opportunity. Non-visible processes get their own, separate limit. An app that is comfortable in the foreground can sit above the line it faces once hidden if it keeps its image caches alive. Release at UI_HIDDEN.

5. Bitmaps: where headroom actually goes

Images remain the usual suspect because decoded size has nothing to do with file size. A 4000 x 3000 photo may be 3 MB as a JPEG and 45.8 MiB as an ARGB_8888 bitmap (4000 x 3000 x 4 bytes).

bitmap-cost

The 3.3 MiB figure assumes an exact target size (for example ImageDecoder.setTargetSize). BitmapFactory.Options.inSampleSize only downsamples by powers of two, so on that path the same photo lands at 2000 x 1500 (11.4 MiB) or 1000 x 750 (2.9 MiB) unless you scale again.

Three rules cover most of the damage:

  1. Decode to the display size, never the source size. Image libraries do this when given real size constraints. Hand-rolled loaders often do not.
  2. Prefer Bitmap.Config.HARDWARE for display-only images. Pixels live in graphics memory and are not copied onto your Java heap. They still count against the process, so this relocates the cost rather than erasing it. It also forbids pixel reads, so it will not suit images you post-process.
  3. Size pools by bytes, not by entry count. An LRU of “100 bitmaps” is meaningless when entries vary by 20x.

Here is a byte-bounded cache with a budget you can change at runtime:

import android.graphics.Bitmap
import android.util.LruCache

class BitmapLruCache(initialMaxBytes: Int) {

    private val lru = object : LruCache<String, Bitmap>(initialMaxBytes) {
        override fun sizeOf(key: String, value: Bitmap): Int = value.allocationByteCount
    }

    operator fun get(key: String): Bitmap? = lru.get(key)
    operator fun set(key: String, value: Bitmap) { lru.put(key, value) }

    fun evictAll() = lru.evictAll()

    /** Shrinks to a fraction of the current ceiling without changing the ceiling. */
    fun evictToFraction(fraction: Float) {
        lru.trimToSize((lru.maxSize() * fraction.coerceIn(0f, 1f)).toInt())
    }

    /** Called when the screen's budget changes, such as on navigation. */
    fun resize(newMaxBytes: Int) = lru.resize(newMaxBytes)

    val usedBytes: Int get() = lru.size()
}
Enter fullscreen mode Exit fullscreen mode

Use allocationByteCount, not byteCount. The first reports the real allocation, including bitmaps that were reused with a smaller logical size, which is exactly the bookkeeping error that makes caches look smaller than they are.

If you use a library such as Coil or Glide, set its memory-cache size as a percentage of the budget you computed, not as a percentage of “available memory”, which is a different number from the one that matters now.

6. A memory budget per screen

Headroom is a shared resource, and screens are the unit people navigate by. Give each screen a byte allowance and make overspending visible in development.

First, derive the total from measurement, not guesswork. Read the foreground limit from am memory-limiter status on your lowest-RAM supported device, then reserve a safety margin for the parts you do not control (WebView, system libraries, other processes in your app). Spend what is left across screens.

screen-budget

The sample figures above are hypothetical. What matters is the shape: a feed is mostly bitmaps, a video screen is mostly codec buffers, and the photo viewer is the one that quietly eats 90% of the allowance.

A lightweight enforcement layer:

import android.util.Log
import java.util.concurrent.ConcurrentHashMap
import java.util.concurrent.atomic.AtomicLong

enum class MemoryCategory { BITMAPS, CACHES, DECODERS, OTHER }

class ScreenBudget(
    val screen: String,
    val maxBytes: Long,
    private val strict: Boolean, // true in debug builds
) {
    private val used = ConcurrentHashMap<MemoryCategory, AtomicLong>()

    fun charge(category: MemoryCategory, bytes: Long) {
        used.getOrPut(category) { AtomicLong() }.addAndGet(bytes)
        check()
    }

    fun release(category: MemoryCategory, bytes: Long) {
        used[category]?.updateAndGet { (it - bytes).coerceAtLeast(0L) } // never go negative
    }

    val totalBytes: Long get() = used.values.sumOf { it.get() }

    private fun check() {
        val total = totalBytes
        if (total <= maxBytes) return
        val breakdown = used.entries.joinToString { "${it.key}=${it.value.get() shr 20}MiB" }
        val message = "Screen '$screen' over budget: ${total shr 20}MiB > ${maxBytes shr 20}MiB ($breakdown)"
        if (strict) error(message) else Log.w("MemoryBudget", message)
    }
}
Enter fullscreen mode Exit fullscreen mode

Wire it into the same places you already allocate: the bitmap cache charges BITMAPS as entries are added, the player charges DECODERS when it allocates a codec, and ViewModel.onCleared() releases everything. In debug, a regression that adds 30 MB to the photo viewer fails a test instead of reaching a low-RAM user six weeks later. In release, it logs to your telemetry so the budget table above can be corrected against reality.

Two practical notes:

  • Budget at navigation boundaries. When the user moves from Feed to Photo viewer, resize caches to the new screen’s allowance and evict the difference. Letting the feed’s cache coexist with a full-size viewer is how screens that each “fit” add up to a kill.
  • Budgets are per process. If you run a :player or :webview process, it needs its own accounting.

7. Failure modes you will actually meet

Testing only on high-RAM hardware. Limits scale with total RAM. A 12 GB flagship may never trigger anything you would notice. Test on a 2 to 4 GB device or an emulator configured with low RAM, and note that the am memory-limiter commands do nothing on devices that do not impose limits.

Trusting the Java heap graph. Android Studio’s heap view will happily show a flat line while native and graphics memory climb. Compare the Java heap to anonPlusSwapMib from the probe in section 2; divergence is the signal.

Ignoring the background limit. Apps that survive foreground use but die minutes after the user switches away are likely holding too much while hidden. Release caches at UI_HIDDEN, and drop timers, players and prefetch jobs along with them.

Multi-process surprises. The adb tooling targets individual PIDs, which suggests enforcement is per process. A media or WebView process that you added “for isolation” now has its own cliff and none of your main-process budgeting.

Treating swap as free. Swapped pages are compressed into zram and still count against the process under the AnonSwap naming. A device that looks fine because it is swapping quietly is closer to the edge than it appears.

Fixing the symptom with largeHeap. It moves the Java cap, slows garbage collection pauses, and leaves the actual limiter exactly where it was.

Long-session creep. Conservative limits target leaks first. A screen that retains 2 MB per visit never fails in a five-minute demo and can fail in a long session, with the exact time depending on navigation cadence and the device’s limit. Run a soak test that loops navigation and watch the anonPlusSwapMib trend, not just the peak.

Silent measurement drift. am memory-limiter ignore all is useful for proving a crash is limiter-related, but leave it on and you will stop seeing the problem you are trying to prevent. Reset with none when you are done.

A checklist to take back to your team

  1. Read the real limit on your weakest device with adb shell am memory-limiter status.
  2. Add the MemoryProbe to a debug overlay and record the lowest headroom per screen.
  3. Read ApplicationExitInfo at launch and report limiter kills, system-pressure kills and Java OOMs separately.
  4. Route onTrimMemory to every rebuildable cache, and release hard at UI_HIDDEN.
  5. Switch image caches to byte-based sizing with allocationByteCount, and decode to display size.
  6. Give every screen a byte budget, enforced strictly in debug and logged in release.
  7. Soak-test navigation loops on a low-RAM device before every release.

The new ceiling is not meant to punish well-behaved apps. It is meant to make the failure deterministic. That is good news for anyone willing to measure: a limit you can read from a shell is a limit you can design for.

🔐 Go Beyond Using Android — Master How It’s Actually Secured

If you’re building, testing, or breaking Android apps, understanding the security model beneath the SDK separates developers who follow best practices from those who truly understand why those practices exist. I highly recommend “Mastering Android Security: From Fundamentals to Advanced Practice.” It’s a comprehensive, architecture-first journey through app sandboxing, cryptography, network defense, reverse engineering, and exploitation — spanning everything from AndroidManifest.xml internals to TrustZone and the Verified Boot chain, with hands-on labs at every step.

Top comments (0)