MemoryBudgetManager
class MemoryBudgetManager
| kotlin.Any | |
| ↳ | android.app.MemoryBudgetManager |
This class is the client interface to memory budgets for applications and processes. A memory budget is a promise by the application or one of its processes that its memory requirements will not exceed some limit. The budget is not a hard limit: it can be exceeded but that will likely cause processes to slow down as they try to release memory and drop below the budget limit.
A budget declaration is not a request for memory from the system, nor does the declaration influence how the system allocates memory to a process. Budgets allow an application to monitor its own resource use.
The memory usage tracked against these budgets includes:
- Anonymous allocations, most commonly the Java heap and native heap.
- File-backed pages (such as files mapped into memory or cached by the process).
The tracked memory usage does not include native graphics buffers or DMA-BUFs.
There are two sets of limits on memory, in addition to the budgets managed through this interface: system limits and manifest budgets (declared using <memory-budget> in AndroidManifest.xml). For each lifecycle state (foreground, perceptible, and background), a dynamic budget set through this interface is clamped to any tighter system or manifest limit in that state, so the stricter ceiling always applies. Setting a dynamic budget that exceeds a system or manifest limit in every lifecycle state for that scope throws an IllegalArgumentException without modifying active limits. Within those ceilings, a dynamic budget can be raised or lowered at any time, or removed using clearPackageBudget() or clearProcessBudget() to resume manifest or system limits.
Unlike <memory-budget> manifest clauses, which specify separate limits for foreground, perceptible, and background states, a dynamic budget sets a single runtime ceiling until updated or cleared, clamped in any state that has a tighter manifest or system limit. Applications deploying new budgets in stages can ship without <memory-budget> in AndroidManifest.xml (or with a conservative manifest ceiling), apply candidate budgets at runtime gated on remote configuration across lifecycle transitions, and call clearProcessBudget() or clearPackageBudget() for instant rollback before graduating proven steady-state budgets into AndroidManifest.xml (where PackageManager.getMemoryBudgets(ApplicationInfo) can inspect static <application> declarations).
A budget must be positive. Attempting to set a budget that is zero or negative throws an IllegalArgumentException.
A package (application) budget applies to all processes in the application as a group (specifically, all processes running under the application's UID). If the application shares a UID with other applications, the budget applies to the aggregate usage of all processes running under that shared UID.
A process budget applies to a single process. It is possible to set a large budget on a process and a small budget on the package; the package budget dominates and the large process budget is irrelevant. This is not an error.
The primary interfaces provided by this class are:
- Memory Budget Configuration:
setPackageBudgetBytes(long)/clearPackageBudget()- Sets or clears the memory budget for the application.setProcessBudgetBytes(long)/clearProcessBudget()- Sets or clears the memory budget for the calling process.
- Memory Budget Queries:
getPackageBudgetBytes()- Returns the current budget for the application.getProcessBudgetBytes()- Returns the current budget for the calling process.
- Memory Usage Queries:
getPackageCurrentUsageBytes()- Returns the aggregate memory usage across all processes in the application package.getProcessCurrentUsageBytes()- Returns the memory usage for the caller's specific process.
- Over-Budget Event Monitoring:
OnOverBudgetListener- Callback interface notified when memory usage exceeds a budget threshold.registerPackageOverBudgetListener(Looper,OnOverBudgetListener)/unregisterPackageOverBudgetListener(OnOverBudgetListener)- Registers or unregisters listeners for package-level budget breaches.registerProcessOverBudgetListener(Looper,OnOverBudgetListener)/unregisterProcessOverBudgetListener(OnOverBudgetListener)- Registers or unregisters listeners for process-level budget breaches.
Performance and Calling Frequency
Budget mutation methods (setProcessBudgetBytes(long), clearProcessBudget(), setPackageBudgetBytes(long), and clearPackageBudget()) make interprocess calls to the system service to update the operating system's underlying memory controller for the process. Budget and usage query methods (getProcessBudgetBytes(), getPackageBudgetBytes(), getProcessCurrentUsageBytes(), and getPackageCurrentUsageBytes()) execute in-process using local native calls to inspect the memory controller directly. While lightweight, these operations are not zero-cost.
Applications should invoke budget mutations and usage queries during discrete lifecycle transitions and task milestones (such as entering or leaving an activity, starting or completing background tasks, or switching operating modes). Applications should avoid invoking these methods in tight loops, audio processing threads, or per-frame render routines.
All budget mutation methods are idempotent. Calling clearProcessBudget() or clearPackageBudget() repeatedly or when no dynamic budget is active is a safe no-op. Similarly, calling setProcessBudgetBytes(long) or setPackageBudgetBytes(long) with an already-active budget value does not trigger redundant system reconfigurations.
Over-Budget Callbacks and Threading
When memory usage exceeds an active budget, the operating system reclaims cold, unused pages first so the active working set continues to fit within the budget. While over-budget reclamation continues, registered OnOverBudgetListener callbacks are invoked repeatedly, debounced to at most once per second for each registered listener.
Because callbacks can fire while the process is under memory pressure, applications should:
- Pass a background
HandlerThreadLoopertoregisterProcessOverBudgetListener(Looper, OnOverBudgetListener)andregisterPackageOverBudgetListener(Looper, OnOverBudgetListener)rather thanLooper.getMainLooper()ornull(which defaults to the mainLooper). While the package or process exceeds its budget, operating system memory reclaim can pause background threads holding locks (such as in logging frameworks, lazy dependency injection singletons, or storage layers), so acquiring locks or performing I/O on the main thread inside anOnOverBudgetListenercallback risks priority inversion and Application Not Responding (ANR) errors. - Keep callback logic fast, lock-free, allocation-free, and idempotent. Avoid blocking I/O, contended locks, or full-process
/procmemory snapshots inside repeated callbacks. InspectgetProcessCurrentUsageBytes()orgetPackageCurrentUsageBytes()instead when checking memory usage. If an application only needs a one-shot notification or wants a longer cooldown between cleanup passes, it can callunregisterProcessOverBudgetListener(OnOverBudgetListener)orunregisterPackageOverBudgetListener(OnOverBudgetListener)from inside the callback, or guard its cleanup with a cooldown timestamp orAtomicBoolean. - Register the listener before tightening a budget with
setProcessBudgetBytes(long)orsetPackageBudgetBytes(long)so the listener does not miss the initial over-budget notification when current memory usage already exceeds the newly configured budget.
Summary
| Nested classes | |
|---|---|
| abstract |
The callback that is notified when a memory budget is exceeded. |
| Constants | |
|---|---|
| static Long |
This value is returned by |
| Public methods | |
|---|---|
| Unit |
Removes the package budget, if any, for the caller's application. |
| Unit |
Removes the process budget, if any, for the caller's process. |
| Long |
Returns the package-scope memory limit in bytes currently applied to the caller's application. |
| Long |
Returns the aggregate memory usage across all processes running under the caller's application UID. |
| Long |
Returns the process-scope memory limit in bytes currently applied to the caller's process. |
| Long |
Returns the current memory usage for the caller's process. |
| Unit |
registerPackageOverBudgetListener(looper: Looper?, listener: MemoryBudgetManager.OnOverBudgetListener)Registers to be notified if the caller's application exceeds its package budget. |
| Unit |
registerProcessOverBudgetListener(looper: Looper?, listener: MemoryBudgetManager.OnOverBudgetListener)Registers to be notified if the caller's process exceeds its process budget. |
| Unit |
setPackageBudgetBytes(budgetBytes: Long)Sets a dynamic memory budget for the caller's application. |
| Unit |
setProcessBudgetBytes(budgetBytes: Long)Sets a dynamic memory budget for the caller's process. |
| Unit |
Unregisters a package budget listener. |
| Unit |
Unregisters a process budget listener. |
Constants
LIMIT_IS_DISABLED
static val LIMIT_IS_DISABLED: Long
This value is returned by getPackageBudgetBytes() and getProcessBudgetBytes() if there is no memory limit associated with the application or process, respectively. This value may not be passed to a function that sets a budget: use the clear functions instead.
Value: -1LPublic methods
clearPackageBudget
fun clearPackageBudget(): Unit
Removes the package budget, if any, for the caller's application. Any manifest budget or system limit that was masked by the package budget is resumed.
This operation is idempotent. Calling this method when no dynamic package budget is set is a safe no-op. This method makes an interprocess call to the system service and is intended for discrete lifecycle transitions rather than tight loops or per-frame routines.
| Exceptions | |
|---|---|
java.lang.SecurityException |
if the caller is not allowed to set budgets, such as from an isolated process |
clearProcessBudget
fun clearProcessBudget(): Unit
Removes the process budget, if any, for the caller's process. Any manifest budget or system limit that was masked by the process budget is resumed.
This operation is idempotent. Calling this method when no dynamic process budget is set is a safe no-op. This method makes an interprocess call to the system service and is intended for discrete lifecycle transitions rather than tight loops or per-frame routines.
| Exceptions | |
|---|---|
java.lang.SecurityException |
if the caller is not allowed to set budgets, such as from an isolated process |
getPackageBudgetBytes
fun getPackageBudgetBytes(): Long
Returns the package-scope memory limit in bytes currently applied to the caller's application. Returns the effective limit from setPackageBudgetBytes(long) (clamped to any tighter active manifest or system limit) if a dynamic budget is set, otherwise the active <application> manifest budget or package system memory limit, or LIMIT_IS_DISABLED if unconstrained or unavailable (such as from an isolated process).
This method reads the kernel cgroup limit in-process (rounded to page size) once applied by the system service.
| Return | |
|---|---|
Long |
the package-scope memory limit for the caller's application in bytes, or LIMIT_IS_DISABLED |
getPackageCurrentUsageBytes
fun getPackageCurrentUsageBytes(): Long
Returns the aggregate memory usage across all processes running under the caller's application UID.
| Return | |
|---|---|
Long |
the current memory usage in bytes. |
| Exceptions | |
|---|---|
java.lang.NumberFormatException |
if there is an error parsing the current usage value from the underlying memory tracking system. |
java.lang.SecurityException |
if the caller is an isolated process or access to the underlying memory tracking system is unavailable. |
java.lang.UnsupportedOperationException |
if memory budgets are not supported. |
getProcessBudgetBytes
fun getProcessBudgetBytes(): Long
Returns the process-scope memory limit in bytes currently applied to the caller's process. Returns the effective limit from setProcessBudgetBytes(long) (clamped to any tighter <process> manifest or system limit in the current lifecycle state) when a dynamic process budget is active, otherwise an active <process> manifest budget, or LIMIT_IS_DISABLED if no per-process limit applies in the current state (default system limits without a dynamic or <process> manifest budget apply at the package scope using getPackageBudgetBytes()).
This method reads the kernel cgroup limit in-process (rounded to page size) once applied by the system service.
| Return | |
|---|---|
Long |
the process-scope memory limit for the caller's process in bytes, or LIMIT_IS_DISABLED |
getProcessCurrentUsageBytes
fun getProcessCurrentUsageBytes(): Long
Returns the current memory usage for the caller's process.
| Return | |
|---|---|
Long |
the current memory usage in bytes. |
| Exceptions | |
|---|---|
java.lang.NumberFormatException |
if there is an error parsing the current usage value from the underlying memory tracking system. |
java.lang.SecurityException |
if access to the underlying memory tracking system is unavailable. |
java.lang.UnsupportedOperationException |
if memory budgets are not supported. |
registerPackageOverBudgetListener
fun registerPackageOverBudgetListener(
looper: Looper?,
listener: MemoryBudgetManager.OnOverBudgetListener
): Unit
Registers to be notified if the caller's application exceeds its package budget. The package budget is based on the aggregate memory usage of all processes running under the same UID. An over-budget event can be triggered by memory allocations in any of these processes.
While the package remains over budget and the operating system continues reclaiming memory, the listener is invoked repeatedly, debounced to at most once per second. Callback implementations should be fast, lock-free, allocation-free, and idempotent, and avoid blocking I/O or full-process /proc memory snapshots. For one-shot notifications or a longer cooldown between cleanup passes, call unregisterPackageOverBudgetListener(OnOverBudgetListener) from inside the callback or guard cleanup work with a cooldown timestamp or AtomicBoolean.
Pass a background HandlerThread Looper rather than Looper.getMainLooper() or null (which defaults to the main Looper) unless the callback touches only lock-free, main-thread UI state. During over-budget memory reclaim, background threads may pause while holding locks (such as in logging frameworks, dependency injection containers, or databases), so acquiring locks or performing I/O on the main thread inside the callback risks priority inversion and Application Not Responding (ANR) errors.
Register this listener before calling setPackageBudgetBytes(long) so the application does not miss the initial over-budget notification when current memory usage already exceeds the newly configured budget.
An OnOverBudgetListener callback can only be registered once.
| Parameters | |
|---|---|
looper |
Looper?: the Looper whose thread dispatches OnOverBudgetListener callbacks, or null to use Looper.getMainLooper() |
listener |
MemoryBudgetManager.OnOverBudgetListener: callback to be notified of an over-budget event. This value cannot be null. |
| Exceptions | |
|---|---|
java.lang.IllegalArgumentException |
if a looper is not provided and one can't be found on the current thread. |
java.lang.IllegalStateException |
if registration fails |
java.lang.SecurityException |
if the caller is an isolated process. |
registerProcessOverBudgetListener
fun registerProcessOverBudgetListener(
looper: Looper?,
listener: MemoryBudgetManager.OnOverBudgetListener
): Unit
Registers to be notified if the caller's process exceeds its process budget. This listener will only be notified of breaches due to memory allocations within the calling process.
While the process remains over budget and the operating system continues reclaiming memory, the listener is invoked repeatedly, debounced to at most once per second. Callback implementations should be fast, lock-free, allocation-free, and idempotent, and avoid blocking I/O or full-process /proc memory snapshots. For one-shot notifications or a longer cooldown between cleanup passes, call unregisterProcessOverBudgetListener(OnOverBudgetListener) from inside the callback or guard cleanup work with a cooldown timestamp or AtomicBoolean.
Pass a background HandlerThread Looper rather than Looper.getMainLooper() or null (which defaults to the main Looper) unless the callback touches only lock-free, main-thread UI state. During over-budget memory reclaim, background threads may pause while holding locks (such as in logging frameworks, dependency injection containers, or databases), so acquiring locks or performing I/O on the main thread inside the callback risks priority inversion and Application Not Responding (ANR) errors.
Register this listener before calling setProcessBudgetBytes(long) so the application does not miss the initial over-budget notification when current memory usage already exceeds the newly configured budget.
An OnOverBudgetListener callback can only be registered once.
| Parameters | |
|---|---|
looper |
Looper?: the Looper whose thread dispatches OnOverBudgetListener callbacks, or null to use Looper.getMainLooper() |
listener |
MemoryBudgetManager.OnOverBudgetListener: callback to be notified of an over-budget event. This value cannot be null. |
| Exceptions | |
|---|---|
java.lang.IllegalArgumentException |
if a looper is not provided and one can't be found on the current thread. |
java.lang.IllegalStateException |
if registration fails |
setPackageBudgetBytes
fun setPackageBudgetBytes(budgetBytes: Long): Unit
Sets a dynamic memory budget for the caller's application. The budget caps cumulative memory use across all processes within the application until updated or cleared with clearPackageBudget(), clamped in each lifecycle state to any tighter system or <application> <memory-budget> state limit. This does not affect any per-process budgets within the application.
budgetBytes must be positive (> 0). Setting a budget that exceeds a system or <application> <memory-budget> limit in every lifecycle state throws an IllegalArgumentException without modifying active limits.
If current package memory usage already exceeds the resulting active limit, an over-budget event is triggered as soon as the new budget is applied. Because listeners only receive events that occur after registration completes, register any OnOverBudgetListener using registerPackageOverBudgetListener(Looper, OnOverBudgetListener) before calling this method so the initial over-budget notification is not missed.
This operation is idempotent. Setting the same budget value consecutively does not trigger redundant system reconfigurations. This method makes an interprocess call to the system service and is intended for discrete lifecycle transitions rather than tight loops or per-frame routines.
| Parameters | |
|---|---|
budgetBytes |
Long: the declared budget, in bytes (must be > 0) Value is 0 or greater |
| Exceptions | |
|---|---|
java.lang.IllegalArgumentException |
if budgetBytes <= 0 or exceeds a system or <memory-budget> limit for the package in every lifecycle state |
java.lang.SecurityException |
if the caller is not allowed to set budgets, such as from an isolated process |
setProcessBudgetBytes
fun setProcessBudgetBytes(budgetBytes: Long): Unit
Sets a dynamic memory budget for the caller's process. The budget caps process memory use across process lifecycle transitions until updated or cleared with clearProcessBudget(), clamped in each lifecycle state to any tighter system or <process> <memory-budget> state limit.
budgetBytes must be positive (> 0). Setting a budget that exceeds a system or <process> <memory-budget> limit in every lifecycle state throws an IllegalArgumentException without modifying active limits.
If current process memory usage already exceeds the resulting active limit, an over-budget event is triggered as soon as the new budget is applied. Because listeners only receive events that occur after registration completes, register any OnOverBudgetListener using registerProcessOverBudgetListener(Looper, OnOverBudgetListener) before calling this method so the initial over-budget notification is not missed.
This operation is idempotent. Setting the same budget value consecutively does not trigger redundant system reconfigurations. This method makes an interprocess call to the system service and is intended for discrete lifecycle transitions rather than tight loops or per-frame routines.
| Parameters | |
|---|---|
budgetBytes |
Long: the declared budget, in bytes (must be > 0) Value is 0 or greater |
| Exceptions | |
|---|---|
java.lang.IllegalArgumentException |
if budgetBytes <= 0 or exceeds a system or <memory-budget> limit for the process in every lifecycle state |
java.lang.SecurityException |
if the caller is not allowed to set budgets, such as from an isolated process |
unregisterPackageOverBudgetListener
fun unregisterPackageOverBudgetListener(listener: MemoryBudgetManager.OnOverBudgetListener): Unit
Unregisters a package budget listener.
| Parameters | |
|---|---|
listener |
MemoryBudgetManager.OnOverBudgetListener: The callback to be notified of an over-budget event. This value cannot be null. |
| Exceptions | |
|---|---|
java.lang.IllegalStateException |
if the listener was not registered. |
unregisterProcessOverBudgetListener
fun unregisterProcessOverBudgetListener(listener: MemoryBudgetManager.OnOverBudgetListener): Unit
Unregisters a process budget listener.
| Parameters | |
|---|---|
listener |
MemoryBudgetManager.OnOverBudgetListener: The callback to be notified of an over-budget event. This value cannot be null. |
| Exceptions | |
|---|---|
java.lang.IllegalStateException |
if the listener was not registered. |