From 530016ff8400fefea8d32e2c7cdb74403afceefb Mon Sep 17 00:00:00 2001 From: Lucas G Date: Mon, 16 Nov 2026 20:19:33 -0300 Subject: [PATCH] Add MemoryBudgetManager sample and best practices --- README.md | 1 + app/build.gradle.kts | 7 +- .../com/example/platform/app/ApiSurface.kt | 7 + .../com/example/platform/app/SampleDemo.kt | 10 + samples/performance/README.md | 25 + samples/performance/memory/README.md | 55 ++ samples/performance/memory/build.gradle.kts | 59 ++ .../memory/src/main/AndroidManifest.xml | 52 ++ .../performance/memory/MemoryBudgetSample.kt | 529 ++++++++++++++++++ settings.gradle.kts | 1 + .../com/example/platform/shared/MinSdkBox.kt | 32 ++ 11 files changed, 777 insertions(+), 1 deletion(-) create mode 100644 samples/performance/README.md create mode 100644 samples/performance/memory/README.md create mode 100644 samples/performance/memory/build.gradle.kts create mode 100644 samples/performance/memory/src/main/AndroidManifest.xml create mode 100644 samples/performance/memory/src/main/java/com/example/platform/performance/memory/MemoryBudgetSample.kt diff --git a/README.md b/README.md index 59a9ea4a..b35d3541 100644 --- a/README.md +++ b/README.md @@ -16,6 +16,7 @@ Browse the samples inside each topic samples folder: - [Connectivity](https://github.com/android/platform-samples/tree/main/samples/connectivity) - [Graphics](https://github.com/android/platform-samples/tree/main/samples/graphics) - [Location](https://github.com/android/platform-samples/tree/main/samples/location) +- [Performance](https://github.com/android/platform-samples/tree/main/samples/performance) - [Privacy](https://github.com/android/platform-samples/tree/main/samples/privacy) - [Storage](https://github.com/android/platform-samples/tree/main/samples/storage) - [User-interface](https://github.com/android/platform-samples/tree/main/samples/user-interface) diff --git a/app/build.gradle.kts b/app/build.gradle.kts index da4ccc82..ea9af86d 100644 --- a/app/build.gradle.kts +++ b/app/build.gradle.kts @@ -23,7 +23,11 @@ plugins { android { namespace = "com.example.platform" - compileSdk = 37 + compileSdk { + version = release(37) { + minorApiLevel = 2 + } + } defaultConfig { applicationId = "com.example.platform" @@ -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")) diff --git a/app/src/main/java/com/example/platform/app/ApiSurface.kt b/app/src/main/java/com/example/platform/app/ApiSurface.kt index 23cbaeec..6ade04fc 100644 --- a/app/src/main/java/com/example/platform/app/ApiSurface.kt +++ b/app/src/main/java/com/example/platform/app/ApiSurface.kt @@ -99,6 +99,12 @@ val MediaVideoApiSurface = ApiSurface( null, ) +val PerformanceMemoryApiSurface = ApiSurface( + "performance-memory", + "Performance - Memory", + null, +) + val PrivacyDataApiSurface = ApiSurface( "privacy-data", "Privacy Data", @@ -219,6 +225,7 @@ val API_SURFACES = listOf( LocationApiSurface, MediaUltraHdrApiSurface, MediaVideoApiSurface, + PerformanceMemoryApiSurface, PrivacyDataApiSurface, PrivacyPermissionsApiSurface, PrivacyTransparencyApiSurface, diff --git a/app/src/main/java/com/example/platform/app/SampleDemo.kt b/app/src/main/java/com/example/platform/app/SampleDemo.kt index a2757752..4a57001b 100644 --- a/app/src/main/java/com/example/platform/app/SampleDemo.kt +++ b/app/src/main/java/com/example/platform/app/SampleDemo.kt @@ -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 @@ -539,6 +540,15 @@ val SAMPLE_DEMOS by lazy { tags = listOf("Transformer"), content = { AndroidFragment() }, ), + 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", diff --git a/samples/performance/README.md b/samples/performance/README.md new file mode 100644 index 00000000..39365c66 --- /dev/null +++ b/samples/performance/README.md @@ -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. +``` diff --git a/samples/performance/memory/README.md b/samples/performance/memory/README.md new file mode 100644 index 00000000..8ea77ca1 --- /dev/null +++ b/samples/performance/memory/README.md @@ -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 `` 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 (``)** — 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 `` 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`). + +## 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. +``` diff --git a/samples/performance/memory/build.gradle.kts b/samples/performance/memory/build.gradle.kts new file mode 100644 index 00000000..fff83987 --- /dev/null +++ b/samples/performance/memory/build.gradle.kts @@ -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")) +} diff --git a/samples/performance/memory/src/main/AndroidManifest.xml b/samples/performance/memory/src/main/AndroidManifest.xml new file mode 100644 index 00000000..e31d0470 --- /dev/null +++ b/samples/performance/memory/src/main/AndroidManifest.xml @@ -0,0 +1,52 @@ + + + + + + diff --git a/samples/performance/memory/src/main/java/com/example/platform/performance/memory/MemoryBudgetSample.kt b/samples/performance/memory/src/main/java/com/example/platform/performance/memory/MemoryBudgetSample.kt new file mode 100644 index 00000000..0bca8b9f --- /dev/null +++ b/samples/performance/memory/src/main/java/com/example/platform/performance/memory/MemoryBudgetSample.kt @@ -0,0 +1,529 @@ +/* + * 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. + */ + +package com.example.platform.performance.memory + +import android.app.MemoryBudgetManager +import android.graphics.Bitmap +import android.graphics.Canvas +import android.graphics.Color +import android.os.Build +import android.os.Looper +import android.util.Log +import android.util.LruCache +import androidx.annotation.RequiresApi +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.FlowRow +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.Spacer +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.height +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.lazy.LazyColumn +import androidx.compose.foundation.lazy.items +import androidx.compose.material3.Button +import androidx.compose.material3.Card +import androidx.compose.material3.CardDefaults +import androidx.compose.material3.FilledTonalButton +import androidx.compose.material3.HorizontalDivider +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.OutlinedButton +import androidx.compose.material3.OutlinedCard +import androidx.compose.material3.Text +import androidx.compose.runtime.Composable +import androidx.compose.runtime.DisposableEffect +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableIntStateOf +import androidx.compose.runtime.mutableStateListOf +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.setValue +import androidx.compose.ui.Modifier +import androidx.compose.ui.platform.LocalContext +import androidx.compose.ui.text.font.FontFamily +import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.unit.dp +import androidx.lifecycle.Lifecycle +import androidx.lifecycle.LifecycleEventObserver +import androidx.lifecycle.compose.LocalLifecycleOwner +import com.example.platform.shared.MinSdkFullBox +import java.text.DateFormat +import java.util.Date +import java.util.Locale +import androidx.core.graphics.createBitmap + +private const val TAG = "MemoryBudgetSample" +private const val BYTES_PER_MB = 1024L * 1024L +private const val GALLERY_BUDGET_BYTES = 96L * BYTES_PER_MB +private const val TIGHT_PRESSURE_TEST_BUDGET_BYTES = 48L * BYTES_PER_MB +private const val MAX_PREVIEW_CACHE_BYTES = 32 * 1024 * 1024 +private const val GALLERY_CACHE_BYTES = 8 * 1024 * 1024 +private const val TILE_DIMENSION_PX = 1024 // 1024 * 1024 * 4 bytes (ARGB_8888) = 4 MB per tile + +private enum class WorkloadMode(val label: String) { + BASELINE("Manifest / Unconstrained"), + GALLERY("Lightweight Gallery (96 MB)"), + TIGHT_TEST("Tight Pressure Test (48 MB)"), +} + +@RequiresApi(Build.VERSION_CODES_FULL.CINNAMON_BUN_2) +private data class MemorySnapshot( + val processUsageBytes: Long = 0L, + val packageUsageBytes: Long = 0L, + val processBudgetBytes: Long = MemoryBudgetManager.LIMIT_IS_DISABLED, + val packageBudgetBytes: Long = MemoryBudgetManager.LIMIT_IS_DISABLED, +) + +@Composable +fun MemoryBudgetSample() { + MinSdkFullBox(minSdkFull = Build.VERSION_CODES_FULL.CINNAMON_BUN_2) { + if ( + (Build.VERSION.SDK_INT >= Build.VERSION_CODES.BAKLAVA) && + (Build.VERSION.SDK_INT_FULL >= Build.VERSION_CODES_FULL.CINNAMON_BUN_2) + ) { + MemoryBudgetContent() + } + } +} + +@RequiresApi(Build.VERSION_CODES_FULL.CINNAMON_BUN_2) +@Composable +private fun MemoryBudgetContent() { + val context = LocalContext.current + val lifecycleOwner = LocalLifecycleOwner.current + val budgetManager = remember(context) { + context.getSystemService(MemoryBudgetManager::class.java) + } + + if (budgetManager == null) { + Column( + modifier = Modifier + .fillMaxSize() + .padding(16.dp), + verticalArrangement = Arrangement.Center, + ) { + Text( + text = "MemoryBudgetManager system service is not available on this device.", + style = MaterialTheme.typography.bodyLarge, + ) + } + return + } + + // High-yield cache target: large Bitmaps that can be evicted quickly under memory pressure. + val previewCache = remember { + object : LruCache(MAX_PREVIEW_CACHE_BYTES) { + override fun sizeOf(key: String, value: Bitmap): Int = value.byteCount + } + } + + var activeMode by remember { mutableStateOf(WorkloadMode.BASELINE) } + var snapshot by remember { mutableStateOf(querySnapshot(budgetManager)) } + var cacheBytes by remember { mutableIntStateOf(previewCache.size()) } + var tileCounter by remember { mutableIntStateOf(0) } + var overBudgetCount by remember { mutableIntStateOf(0) } + val eventLogs = remember { mutableStateListOf() } + + fun appendLog(message: String) { + val time = DateFormat.getTimeInstance().format(Date()) + eventLogs.add(0, "[$time] $message") + if (eventLogs.size > 20) { + eventLogs.removeAt(eventLogs.lastIndex) + } + } + + fun refreshTelemetry() { + // Query on demand at discrete milestones rather than polling in a continuous loop. + snapshot = querySnapshot(budgetManager) + cacheBytes = previewCache.size() + } + + // Best practice for OnOverBudgetListener: + // 1. Keep it fast to provide immediate relief. + // 2. Avoid allocating new objects or spawning threads inside the callback. + // 3. Target high-yield caches such as large Bitmaps or render buffers. + val overBudgetListener = remember(budgetManager, previewCache) { + MemoryBudgetManager.OnOverBudgetListener { budgetBytes -> + Log.w(TAG, "Over-budget callback triggered (limit=${formatMb(budgetBytes)})") + previewCache.evictAll() + overBudgetCount += 1 + cacheBytes = 0 + snapshot = querySnapshot(budgetManager) + } + } + + DisposableEffect(lifecycleOwner, budgetManager, overBudgetListener, previewCache) { + var isRegistered = false + + fun unregisterListener() { + if (isRegistered) { + try { + budgetManager.unregisterProcessOverBudgetListener(overBudgetListener) + } catch (e: IllegalStateException) { + Log.w(TAG, "Process listener was not registered", e) + } finally { + isRegistered = false + } + } + } + + val observer = LifecycleEventObserver { _, event -> + when (event) { + Lifecycle.Event.ON_START -> { + if (!isRegistered) { + budgetManager.registerProcessOverBudgetListener( + Looper.getMainLooper(), + overBudgetListener, + ) + isRegistered = true + refreshTelemetry() + appendLog("ON_START: Registered OnOverBudgetListener on main Looper.") + } + } + + Lifecycle.Event.ON_STOP -> { + unregisterListener() + // Clear dynamic overrides and cached bitmaps when leaving the screen. + budgetManager.clearProcessBudget() + previewCache.evictAll() + cacheBytes = 0 + activeMode = WorkloadMode.BASELINE + appendLog("ON_STOP: Unregistered listener and cleared dynamic process budget.") + } + + else -> Unit + } + } + lifecycleOwner.lifecycle.addObserver(observer) + + onDispose { + lifecycleOwner.lifecycle.removeObserver(observer) + unregisterListener() + budgetManager.clearProcessBudget() + previewCache.evictAll() + } + } + + fun applyDynamicBudget(targetBytes: Long, mode: WorkloadMode) { + try { + // Idempotent cross-process IPC: calling with the same value is a safe no-op. + budgetManager.processBudgetBytes = targetBytes + activeMode = mode + if (mode == WorkloadMode.GALLERY) { + previewCache.trimToSize(GALLERY_CACHE_BYTES) + } + refreshTelemetry() + appendLog("Applied ${formatMb(targetBytes)} dynamic process budget (${mode.label}).") + } catch (e: IllegalArgumentException) { + Log.e(TAG, "Failed to apply dynamic budget", e) + appendLog("Rejected budget ${formatMb(targetBytes)}: ${e.message}") + } + } + + fun enterEditingCanvas() { + // Restore the manifest ceiling (or unconstrained baseline if no manifest tag is set). + // Calling clearProcessBudget() repeatedly is an idempotent no-op. + budgetManager.clearProcessBudget() + activeMode = WorkloadMode.BASELINE + refreshTelemetry() + appendLog("Cleared dynamic budget to restore baseline/manifest ceiling.") + } + + fun testExceedingBudgetRejection() { + val excessiveBudgetBytes = Long.MAX_VALUE / 2 + try { + budgetManager.processBudgetBytes = excessiveBudgetBytes + } catch (e: IllegalArgumentException) { + appendLog( + "Caught expected IllegalArgumentException for above-ceiling budget: ${e.message}", + ) + } + } + + fun allocatePreviewTile() { + val nextId = tileCounter + 1 + tileCounter = nextId + val bitmap = createBitmap(TILE_DIMENSION_PX, TILE_DIMENSION_PX) + // Touch pixels so memory pages are faulted in and counted toward resident usage. + Canvas(bitmap).drawColor(Color.rgb((nextId * 47) % 255, 120, 200)) + previewCache.put("tile_$nextId", bitmap) + refreshTelemetry() + appendLog("Cached 4 MB preview tile #$nextId (cache=${formatMb(cacheBytes.toLong())}).") + } + + LazyColumn( + modifier = Modifier + .fillMaxSize() + .padding(16.dp), + verticalArrangement = Arrangement.spacedBy(12.dp), + ) { + item { + Text( + text = "App Memory Budgets (API 37.2)", + style = MaterialTheme.typography.headlineSmall, + fontWeight = FontWeight.SemiBold, + ) + Spacer(modifier = Modifier.height(4.dp)) + Text( + text = "Demonstrates lifecycle-driven dynamic budgets, on-demand telemetry, and " + + "high-yield cache eviction with MemoryBudgetManager.", + style = MaterialTheme.typography.bodyMedium, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + } + + item { + Card( + modifier = Modifier.fillMaxWidth(), + colors = CardDefaults.cardColors( + containerColor = MaterialTheme.colorScheme.surfaceVariant, + ), + ) { + Column( + modifier = Modifier.padding(16.dp), + verticalArrangement = Arrangement.spacedBy(6.dp), + ) { + Text( + text = "On-Demand Telemetry", + style = MaterialTheme.typography.titleMedium, + ) + TelemetryRow("Active Mode", activeMode.label) + TelemetryRow( + "Process Usage", + formatMb(snapshot.processUsageBytes), + ) + TelemetryRow( + "Process Budget", + formatBudget(snapshot.processBudgetBytes), + ) + TelemetryRow( + "Package Usage", + formatMb(snapshot.packageUsageBytes), + ) + TelemetryRow( + "Package Budget", + formatBudget(snapshot.packageBudgetBytes), + ) + TelemetryRow( + "Preview Bitmap Cache", + "${formatMb(cacheBytes.toLong())} / ${formatMb(MAX_PREVIEW_CACHE_BYTES.toLong())}", + ) + TelemetryRow("Over-Budget Callbacks", overBudgetCount.toString()) + Spacer(modifier = Modifier.height(4.dp)) + OutlinedButton( + onClick = { + refreshTelemetry() + appendLog("Refreshed telemetry on demand.") + }, + ) { + Text("Refresh Telemetry") + } + } + } + } + + item { + OutlinedCard(modifier = Modifier.fillMaxWidth()) { + Column( + modifier = Modifier.padding(16.dp), + verticalArrangement = Arrangement.spacedBy(8.dp), + ) { + Text( + text = "1. Discrete Workload Transitions", + style = MaterialTheme.typography.titleMedium, + ) + Text( + text = "Update budgets only at discrete navigation or lifecycle " + + "milestones, never in tight loops or per-frame render routines.", + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + FlowRow( + horizontalArrangement = Arrangement.spacedBy(8.dp), + verticalArrangement = Arrangement.spacedBy(8.dp), + ) { + Button( + onClick = { + applyDynamicBudget(GALLERY_BUDGET_BYTES, WorkloadMode.GALLERY) + }, + ) { + Text("Gallery Mode (96 MB)") + } + FilledTonalButton(onClick = ::enterEditingCanvas) { + Text("Editing Canvas (Clear)") + } + OutlinedButton( + onClick = { + applyDynamicBudget( + TIGHT_PRESSURE_TEST_BUDGET_BYTES, + WorkloadMode.TIGHT_TEST, + ) + }, + ) { + Text("Tight Limit (48 MB)") + } + OutlinedButton(onClick = ::testExceedingBudgetRejection) { + Text("Test Ceiling Error") + } + } + } + } + } + + item { + OutlinedCard(modifier = Modifier.fillMaxWidth()) { + Column( + modifier = Modifier.padding(16.dp), + verticalArrangement = Arrangement.spacedBy(8.dp), + ) { + Text( + text = "2. High-Yield Cache Simulation", + style = MaterialTheme.typography.titleMedium, + ) + Text( + text = "Allocate 4 MB ARGB_8888 Bitmap tiles to observe resident usage " + + "and proactive OnOverBudgetListener eviction.", + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + FlowRow( + horizontalArrangement = Arrangement.spacedBy(8.dp), + verticalArrangement = Arrangement.spacedBy(8.dp), + ) { + Button(onClick = ::allocatePreviewTile) { + Text("Cache 4 MB Bitmap Tile") + } + OutlinedButton( + onClick = { + previewCache.evictAll() + refreshTelemetry() + appendLog("Manually evicted all cached preview Bitmaps.") + }, + ) { + Text("Evict Cache") + } + } + } + } + } + + item { + OutlinedCard(modifier = Modifier.fillMaxWidth()) { + Column( + modifier = Modifier.padding(16.dp), + verticalArrangement = Arrangement.spacedBy(6.dp), + ) { + Text( + text = "Manifest & Runtime Best Practices", + style = MaterialTheme.typography.titleMedium, + ) + Text( + text = "• Prefer in AndroidManifest.xml (release builds " + + "only to avoid debug swap churn).", + style = MaterialTheme.typography.bodySmall, + ) + Text( + text = "• Order manifest clauses from general to specific: the last " + + "applicable clause takes effect.", + style = MaterialTheme.typography.bodySmall, + ) + Text( + text = "• Runtime budgets can only tighten the manifest ceiling; " + + "exceeding it throws IllegalArgumentException.", + style = MaterialTheme.typography.bodySmall, + ) + Text( + text = "• Keep OnOverBudgetListener fast, allocation-free, and focused " + + "on large caches (Bitmaps, render buffers, mapped files).", + style = MaterialTheme.typography.bodySmall, + ) + } + } + } + + item { + Text( + text = "Event Log", + style = MaterialTheme.typography.titleMedium, + ) + HorizontalDivider(modifier = Modifier.padding(top = 4.dp)) + } + + if (eventLogs.isEmpty()) { + item { + Text( + text = "No events recorded yet.", + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + } + } else { + items(eventLogs) { entry -> + Text( + text = entry, + style = MaterialTheme.typography.bodySmall, + fontFamily = FontFamily.Monospace, + ) + } + } + } +} + +@Composable +private fun TelemetryRow(label: String, value: String) { + Row( + modifier = Modifier.fillMaxWidth(), + horizontalArrangement = Arrangement.SpaceBetween, + ) { + Text( + text = label, + style = MaterialTheme.typography.bodyMedium, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + Text( + text = value, + style = MaterialTheme.typography.bodyMedium, + fontWeight = FontWeight.Medium, + fontFamily = FontFamily.Monospace, + ) + } +} + +@RequiresApi(Build.VERSION_CODES_FULL.CINNAMON_BUN_2) +private fun querySnapshot(budgetManager: MemoryBudgetManager): MemorySnapshot { + return MemorySnapshot( + processUsageBytes = budgetManager.processCurrentUsageBytes, + packageUsageBytes = budgetManager.packageCurrentUsageBytes, + processBudgetBytes = budgetManager.processBudgetBytes, + packageBudgetBytes = budgetManager.packageBudgetBytes, + ) +} + +@RequiresApi(Build.VERSION_CODES_FULL.CINNAMON_BUN_2) +private fun formatBudget(bytes: Long): String { + return if (bytes == MemoryBudgetManager.LIMIT_IS_DISABLED) { + "Unconstrained (LIMIT_IS_DISABLED)" + } else { + formatMb(bytes) + } +} + +private fun formatMb(bytes: Long): String { + val mb = bytes / BYTES_PER_MB.toDouble() + return String.format(Locale.US, "%.1f MB", mb) +} diff --git a/settings.gradle.kts b/settings.gradle.kts index 729136e4..d4ba959c 100644 --- a/settings.gradle.kts +++ b/settings.gradle.kts @@ -57,6 +57,7 @@ include(":samples:graphics:ultrahdr") include(":samples:location") include(":samples:media:ultrahdr") include(":samples:media:video") +include(":samples:performance:memory") include(":samples:privacy:data") include(":samples:privacy:permissions") include(":samples:privacy:transparency") diff --git a/shared/src/main/java/com/example/platform/shared/MinSdkBox.kt b/shared/src/main/java/com/example/platform/shared/MinSdkBox.kt index fe2dc07d..2f186834 100644 --- a/shared/src/main/java/com/example/platform/shared/MinSdkBox.kt +++ b/shared/src/main/java/com/example/platform/shared/MinSdkBox.kt @@ -54,4 +54,36 @@ fun MinSdkBox(modifier: Modifier = Modifier, minSdk: Int, content: @Composable ( } else { content() } +} + +@Composable +fun MinSdkFullBox( + modifier: Modifier = Modifier, + minSdkFull: Int, + content: @Composable () -> Unit, +) { + val isSupported = Build.VERSION.SDK_INT >= Build.VERSION_CODES.BAKLAVA && + Build.VERSION.SDK_INT_FULL >= minSdkFull + if (!isSupported) { + val major = minSdkFull / 100_000 + val minor = minSdkFull % 100_000 + Column( + modifier = modifier.fillMaxSize(), + horizontalAlignment = Alignment.CenterHorizontally, + verticalArrangement = Arrangement.Center, + ) { + Icon( + painter = painterResource(R.drawable.round_warning_24), + contentDescription = null, + modifier = Modifier.size(64.dp), + ) + Spacer(Modifier.height(18.dp)) + Text( + text = "Your device's Android Version is lower than the required SDK version for this sample: $major.$minor", + textAlign = TextAlign.Center, + ) + } + } else { + content() + } } \ No newline at end of file