Android Engineering

Use Android Studio build diagnostics, Logcat, debugger, CPU and memory profilers, Perfetto, and GPU tools through practical guides and code questions.

~49 min reading~54 min practice estimate
Suggest content

Android Studio Debugging and Profiling Questionnaire

🟪 Language syntax · 🟦 Tools/APIs · 🟩 Correct pattern · 🟥 Bug · 🟨 Gotcha · 🧠 Explanation

Use Android Studio to turn a symptom into evidence, a focused correction, and a repeatable check. This practical guide and independent question bank cover build failures, runtime debugging, CPU/GPU investigation, and memory ownership. They are self-authored study material, not an official assessment.

Assumptions and verification: Kotlin/JVM Android app, Gradle Wrapper, Android Gradle Plugin (AGP), and optional Jetpack Compose. Official Android, Kotlin, and Gradle references were checked on 22 October 2026. Tool names and feature availability depend on the installed IDE, plugin, device, OS, driver, build variant, and permissions. Logs, code, and timings below are illustrative exercises: no Android project was compiled, device debugged, or profiler measurement performed for this lesson.

Related practice: Android code and architecture, mobile incident response and performance, and cross-platform technical leadership. Try four questions and one hands-on reproduction in a suggested 45-minute session; this configured practice duration is separate from reading time.

Practical guide: choose the next tool

Start with the layer where the failure occurs. An app that never compiles has no useful runtime Logcat investigation; a slow frame requires a timeline, not just a screenshot.

Tool / what it answersWhere to openHow to use itInterpret → next action
Build output: why did this variant fail?Build tool window; selected failed taskExpand the task, read its concrete diagnostic and file/line; retain relevant causesClassify sync, Kotlin, resource, manifest, dependency, dex, or R8 failure → fix the owning input
Logcat: what happened at runtime?View → Tool Windows → LogcatSelect device/process, filter package and severity, reproduce onceMatch exception/cause and first relevant app frame → breakpoint or regression test
Debugger: which values/path caused it?Debug the debuggable variantPause at the ownership boundary; inspect locals, callers, and threadsCompare actual state with invariant → correct mutation/validation
Database Inspector: what was persisted?View → Tool Windows → App Inspection → Database InspectorSelect process/database; inspect account IDs, versions, pending rows with read queriesCorrect row but wrong UI → investigate observation; wrong row → inspect write/transaction
Network Inspector: what request/result occurred?App Inspection → Network InspectorSelect time range/request; inspect timing, status, and redacted payload shapeSeparate no request, server rejection, and stale publication → instrument the missing boundary
Layout Inspector / Compose tools: what UI exists?Layout Inspector in Running Devices; IDE entry variesInspect hierarchy, bounds/attributes, recomposition and skip countsIdentify wrong identity/layout/state input → test the responsible UI contract
System Trace: why was a deadline missed?View → Tool Windows → Profiler; system-trace taskCapture one short journey; select slow frames and correlate threadsMain CPU, runnable delay, blocking, RenderThread, or supported GPU-completion evidence → targeted capture
CPU call-stack recording: where is CPU work spent?Profiler task for CPU call stacks / method recordingRecord the interval; inspect thread, bottom-up self time, and callersExpensive work on critical path → reduce, defer, or safely move that work
Heap dump: who retains these objects?Profiler → Analyze Memory Usage (Heap Dump)Use debuggable build; repeat navigation, capture, inspect referencesLong-lived root reaches obsolete screen → repair ownership and recapture
Allocation recording: what creates churn?Profiler → Java/Kotlin or Native Allocations taskRecord a bounded interval; group by allocation stackHigh temporary allocation or unreleased native ownership → change allocation/lifetime, verify separately
HWUI bars / AGI: which rendering hypothesis fits?Device Developer Options / Android GPU InspectorUse bars for triage; validate AGI device/API support for detailed capturesCPU-side bars versus GPU workloads are different evidence → correlate before changing graphics

Logcat filters such as package:mine level:ERROR narrow a noisy stream; keep context around the failure, including process restarts. Do not log credentials or full private payloads. Android Logcat guide.

Database Inspector requires a supported database configuration: its documented support is the platform SQLite library on API 26+, not every bundled/custom SQLite implementation. Network Inspector supports HttpsURLConnection and OkHttp paths; an empty inspector is not proof of no network traffic. Database Inspector, Network Inspector.

Practical guide: fix build errors from their first useful cause

  1. Record branch/revision, selected module/variant, Gradle Wrapper, AGP/Kotlin plugin, SDK, and Gradle JDK. Reproduce the same task locally before changing unrelated settings.
  2. Expand the failed task's output. Read the first meaningful cause in that task, not simply the first red line in interleaved parallel output. Follow Caused by chains until the actionable diagnostic appears; keep the file/line and relevant preceding messages.
  3. Separate IDE Gradle sync/configuration from task execution. A successful sync imports the model; it does not prove every source set compiles. A compiler error is not fixed by changing the device/emulator.
  4. Use the wrapper and actual variant. Add --stacktrace when the normal diagnostic omits the cause; use --info selectively. Review logs for secrets before sharing them. Fix one cause and rerun the failed task plus the affected build/test path.

Illustrative commands for a module named app, with a debug variant; change these names to match the project. They are examples to run in the target project, not commands executed for this lesson.

BASH
./gradlew :app:assembleDebug --stacktrace
./gradlew :app:dependencies --configuration debugRuntimeClasspath
./gradlew :app:dependencyInsight --dependency example-library --configuration debugRuntimeClasspath

dependencies shows the resolved graph; dependencyInsight explains why a dependency/version was selected. Inspect compile and runtime configurations as the failure requires. Avoid blind exclusions, forced versions, cache deletion, or an IDE reinstall before establishing the cause. Gradle dependency reports, Gradle command-line diagnostics.

Keyword or failure stageMeaning to investigateUseful correction boundary
Gradle sync, plugin resolution, unsupported JDKConfiguration/toolchain/repository problemWrapper–AGP–Kotlin compatibility, configured Gradle JDK, repository access
Unresolved reference, type mismatch, nullable receiverKotlin source/visible classpath issueFile/line, imports, generated sources, module/source set, compile dependency
AAPT2, resource linking failedResource compilation/linking issueActual XML/resource symbol, namespace, variant resources, dependency
Manifest merger failedVariant/library manifests disagreeMerged Manifest provenance; deliberate attribute resolution
Duplicate class, dex mergeSame class reaches packaging more than onceResolved runtime graph, duplicate jars/modules, incompatible library packaging
R8 missing classReferenced type unavailable to optimizer analysisRequired dependency or a narrowly justified optional-reference configuration
Release-only reflection crashRuntime entry point may be renamed/removedExact release artifact, consumer rules, targeted keep contract, matching mapping

The JVM that runs Gradle, Kotlin/Java bytecode targets, Android compileSdk, and minSdk are distinct settings. Raising minSdk cannot repair the wrong JDK running the build. Android build JDK guide, Kotlin Gradle compiler options.

If evidence points to an IDE/compiler/plugin defect, preserve exact IDE/AGP/Gradle/Kotlin/JDK versions, the variant, first useful diagnostic, and a minimal reproducer. Check the pinned versions' supported compatibility requirements and issue/release notes, then prepare a sanitized report. An editor-only error with a successful equivalent wrapper build differs from a compiler crash reproduced by both. Invalidate Caches or delete caches only for an established cache/index problem; neither is a default source-code fix. AGP release and compatibility documentation.

Practical guide: control the debugger deliberately

Debug the intended debuggable process/build. Set a gutter breakpoint on executable code, reproduce, then inspect its verified/disabled/muted status if it does not stop. Check that the path was reached, source matches the installed artifact, and the debugger type matches Kotlin/JVM or native code. R8/inlining/optimization can remove variables or alter source stepping; reproduce behavior in the real release configuration as well as a diagnostic build.

Breakpoint optionHow to apply it effectively
ConditionOpen breakpoint properties; use a pure ID/state predicate to stop on the relevant operation
Suspend thread / allSelect the policy exposed by that breakpoint/debugger; thread permits others to run, all changes global scheduling
Logging without suspensionDisable Suspend and enable message/expression logging when supported; keep expressions pure and payloads private
Pass count / hit-count filterUse only when offered; check semantics—IntelliJ's Pass count repeats every N qualifying hits, not “ignore N once”
Exception caught / uncaughtChoose the specific exception and offered filters; caught exceptions can be normal control flow

These are JetBrains JVM debugger concepts; Android Studio's bundled version, breakpoint type, runtime, and native debugger determine which options actually appear. Logging breakpoints still add overhead. JetBrains breakpoint properties.

In the Debug window, select the thread and stack frame before interpreting locals. Step Over advances past a call; Step Into follows it; Step Out returns to its caller; Resume runs to the next stop. Use watches for stable read-only values and Evaluate Expression only when execution is intentional. A pause perturbs races and may retain inspected objects; disconnect before interpreting a retention experiment. Android Debug window and stepping.

Practical guide: measure CPU, graphics, and memory honestly

For timing, prefer a representative release-like profileable build and physical target devices; record OS, refresh rate, thermal condition, cache/network state, and journey. Android Studio's complete-data/debuggable path is appropriate when required for debugger, heap, or Java/Kotlin allocation visibility, but its timings are not interchangeable with low-overhead profiling. Compare the same capture mode before and after. Android Profiler requirements.

CPU/system trace: Start recording immediately before a reproducible interaction, stop just after it, select the delayed frame/operation, then inspect main, RenderThread, worker threads, scheduling, and lock/IO boundaries. CPU call stacks explain work inside an interval; a system trace explains coordination and waiting. Distinguish self time from total time including callees; an aggregated flame chart's horizontal axis is not chronological. System traces, trace interpretation.

Read the CPU-percent legend: Studio's documented system-trace CPU chart uses total available CPU capacity; other tools may normalize per core. A busy main core can coexist with a low aggregate percentage. Running means scheduled CPU work; runnable means ready but not scheduled; sleeping/blocked time is not CPU execution. Use Android Studio's trace view or a supported Perfetto capture/viewer to correlate the interval. Perfetto Android tracing.

Graphics: Input/state → composition or View traversal → measure/layout/draw-command recording → RenderThread/command submission → GPU execution → composition/presentation is a useful orientation; implementations and overlaps vary. The display interval is approximately 1000 / refreshRateHz milliseconds: 16.67 at 60 Hz, 11.11 at 90 Hz, 8.33 at 120 Hz. These are theoretical intervals, not measured app results or universally available CPU budgets. Read actual frame deadlines and pipeline overlap.

Enable device Developer Options → Profile GPU Rendering / Profile HWUI rendering → On screen as bars for quick framework-rendering triage. Despite its name, the documented bars measure CPU-side stages, including waits while submitting graphics work; they do not directly measure GPU utilization. The historic 16.67 ms reference line is not universal for high-refresh displays or every rendering path. HWUI rendering inspection.

For a supported framework-rendered package, adb shell dumpsys gfxinfo com.example.app framestats exposes frame statistics; replace the example package and delimit the tested journey. These statistics complement a trace and are not GPU hardware counters or universal coverage of custom rendering paths. Android dumpsys gfxinfo.

For detailed supported graphics work, validate Android GPU Inspector's device/driver and app requirements, select an appropriate frame capture, reproduce, and inspect relevant commands/counters. Frame capture is especially relevant to supported Vulkan/OpenGL ES workloads; it is not a universal Compose profiler. Missing GPU tracks may reflect capture support, not zero GPU work. App debuggability, graphics API, Android version, driver validation, and permissions differ by tool. The current AGI quickstart recommends Android Performance Analyzer, available in public beta, for system profiling; this lesson's general timeline workflow uses Studio/Perfetto. AGI capabilities, AGI setup and current system-tool guidance.

Rendering keywords: RenderThread submits framework rendering work; VSYNC relates to display synchronization; jank means missed/irregular frame delivery. Overdraw draws a pixel repeatedly within a frame. Enable the device's overdraw visualization for a hypothesis, then inspect whether removing redundant backgrounds/layers improves the measured journey. Translucency and effects can be intentional, and overdraw colors are not a GPU-cost benchmark. FPS/jank alone cannot establish whether CPU, GPU, scheduling, or synchronization caused the delay. Android overdraw investigation.

Memory: Reproduce repeated open/close cycles, return to an equivalent idle state, and inspect whether expected-lived objects remain reachable. A heap snapshot answers retention; allocation stacks answer creation/churn; native allocation recordings answer native ownership. A sawtooth managed heap can be normal GC, while growing retained screen instances deserve investigation. Full allocation recording can slow the app; sampled mode trades detail for lower overhead. Do not infer process memory, graphics buffers, or all native allocations from Java heap size alone. Heap analysis, managed allocations, native allocations.

Questions

STUDIO-01 — Which message identifies the actionable Kotlin build error?

The build reports a nullable-receiver error and then several general failure messages. Treat the output as schematic diagnostic evidence.

TEXT
> Task :app:compileDebugKotlin FAILED
e: CheckoutScreen.kt:42: Only safe (?.) or non-null asserted (!!.) calls
   are allowed on a nullable receiver of type Customer?
Execution failed for task ':app:compileDebugKotlin'.
Compilation error. See log for more details.
BUILD FAILED
Optional follow-up questions
  • Which source value and expected screen state would you inspect at the reported line?
  • Why is rerunning the build without identifying the specific error unlikely to help?

STUDIO-02 — Why can Gradle work in a terminal but fail to sync in Android Studio?

The same revision builds in one terminal, while Android Studio reports an incompatible Java runtime during sync.

Optional follow-up questions
  • Which toolchain values must match, and which IDE runtime can differ?
  • How would you trace an unresolved PaymentsClient to its source set, module, and dependency scope?

STUDIO-03 — How should you investigate a duplicate-class packaging error?

The selected debug variant finds the same Parser class in two packaged libraries.

TEXT
> Task :app:checkDebugDuplicateClasses FAILED
Duplicate class com.example.codec.Parser found in modules
codec-core.jar and legacy-client.jar
Optional follow-up questions
  • Which dependency-report command would show the resolved paths for that variant?
  • How would you verify a targeted dependency change without hiding a required class?

STUDIO-04 — How can you distinguish resource-linking and manifest-merger failures?

These schematic messages come from two different Android build stages.

TEXT
Android resource linking failed
checkout.xml:18: error: resource string/pay_now not found.
​
Manifest merger failed:
Attribute application@allowBackup has conflicting values
in the app manifest and a library manifest.
Optional follow-up questions
  • Why should you fix the source resource or reference instead of generated R output?
  • When is tools:replace justified, and what policy could a blind override hide?

STUDIO-05 — Does a release-only failure always need an R8 keep rule?

One release fails during R8 with a missing-class diagnostic; another builds but throws NoSuchMethodException when using reflection.

Optional follow-up questions
  • What evidence would distinguish dependency resolution from removal of a reflection entry point?
  • How would you preserve and apply the mapping file for the failing production build?

STUDIO-06 — Can evaluating a debugger expression change the application?

While paused before checkout submission, a developer proposes evaluating viewModel.submitOrder() to inspect its result.

Optional follow-up questions
  • Which watches and breakpoint conditions would avoid causing another submission?
  • How should exception breakpoints and suspend policy support the investigation?

STUDIO-07 — Where should you begin investigating this crash trace?

The schematic trace wraps a number-parsing failure in a higher-level checkout-rendering exception.

TEXT
FATAL EXCEPTION: main
java.lang.IllegalStateException: Unable to render checkout
  at CheckoutPresenter.render(CheckoutPresenter.kt:88)
Caused by: java.lang.NumberFormatException: For input string: ""
  at java.lang.Integer.parseInt(Integer.java:...)
  at CheckoutMapper.quantity(CheckoutMapper.kt:21)
Optional follow-up questions
  • Which exception breakpoint would help capture the bad value before it is wrapped?
  • What missing input-contract facts should be checked before changing the parser?

STUDIO-08 — How can fresh server data fail to reach the screen?

The server returned a newer record, but the current account’s screen still displays an older value.

Optional follow-up questions
  • Which request ID, account, and data version should you correlate across Network Inspector, Database Inspector, and the debugger?
  • How would you distinguish a failed write from a stale observer or obsolete response?

STUDIO-09 — Does frequent Compose recomposition prove a performance defect?

A scrolling form recomposes frequently, and selecting a row sometimes affects a different row after insertion.

Optional follow-up questions
  • What do item keys, observable state, and bounds inspection each tell you?
  • Which reproducible interaction and frame measurements would show whether the recomposition is actually costly?

STUDIO-10 — Why does a coroutine containing blocking work freeze the UI?

Load is called on the main thread. The coroutine sleeps and then reads a cached report through a blocking API.

KOTLIN
fun load() {
    viewModelScope.launch {
        Thread.sleep(3_000)
        state.value = repository.readCachedReportBlocking()
    }
}
Optional follow-up questions
  • Which CPU or system trace would show the blocked main thread?
  • Why can low average CPU usage still accompany an unresponsive application?

STUDIO-11 — How can you tell computation, blocking, and suspension apart?

Three equally slow requests spend their time differently: one parses on main, one waits for a worker-held monitor, and one suspends in an asynchronous HTTP call.

Optional follow-up questions
  • Which capture would identify the active parser, blocked waiter, or asynchronous request?
  • How would you fix a lock dependency without merely moving the thread that waits?

STUDIO-12 — Do tall rendering bars identify an expensive GPU shader?

Profile HWUI rendering bars spike during scrolling, but a CPU recording shows no single obviously expensive method.

Optional follow-up questions
  • What should a System Trace establish before you use Android GPU Inspector?
  • Which device, capture, and graphics-track prerequisites would you check before making a GPU claim?

STUDIO-13 — Is a 12-millisecond frame always fast enough?

An illustrative report claims that 12 milliseconds per frame proves smooth rendering on every display.

Optional follow-up questions
  • What are the approximate frame intervals at 60, 90, and 120 Hz?
  • Why can adding CPU and GPU durations misrepresent a pipelined frame, and which before-and-after timeline should you compare?

STUDIO-14 — How can a heap dump show why a closed Activity is still retained?

Subscriptions lives for the process and retains callbacks. This Activity registers a callback when it is created.

KOTLIN
class DetailsActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        Subscriptions.add { title = "Updated" }
    }
}
Optional follow-up questions
  • Which registration and removal lifetimes should match?
  • What repeated navigation sequence and idle point would make the heap comparison meaningful?

STUDIO-15 — Why can process memory grow while the Kotlin and Java heap stays stable?

An image-heavy screen raises total process memory over repeated visits even though Kotlin object counts look stable.

Optional follow-up questions
  • Which supported tools would reveal native allocations, bitmap size and lifetime, or graphics resources?
  • How would you distinguish a bounded cache or temporary peak from continuing retention?

STUDIO-16 — Can allocation profiling itself make the app slower?

The app stutters only while complete-data profiling and full Java or Kotlin allocation recording are attached.

Optional follow-up questions
  • Which build settings are appropriate for heap diagnosis versus representative timing?
  • How would sampled recording and preserved symbols support a fair comparison?

STUDIO-17 — Why can a breakpoint hide an out-of-order response bug?

Every search and state update runs on main, but the suspending repository calls can finish out of order.

KOTLIN
fun search(query: String) {
    viewModelScope.launch {
        results.value = repository.search(query)
    }
}
Optional follow-up questions
  • How would a fake repository finish the old request last deterministically?
  • Why do main-thread access and a thread-safe state holder not by themselves enforce latest-result behavior?

STUDIO-18 — What evidence should support releasing a performance fix?

A team proposes moving work to IO and increasing the heap after users report freezes and memory growth.

Optional follow-up questions
  • Which CPU, memory, and graphics evidence is relevant to the actual symptom?
  • Where can StrictMode help, and which release, mitigation, or rollback checks remain necessary?

Answer key

STUDIO-01 — Answer

Short answer: The useful diagnostic names the source file, line, and nullable Customer value; BUILD FAILED only reports the final outcome. Open the reported expression and decide what a missing customer should mean before choosing a null-handling fix. Adding a forced non-null assertion can move the same problem from build time to a crash.

Detailed explanation:

Illustrative corrected UI boundary: render the absent state explicitly instead of force-unwrapping the customer. Customer is an app model.

KOTLIN
@Composable
fun CheckoutHeader(customer: Customer?) {
    if (customer == null) {
        Text("Sign in to continue")
        return
    }
    Text(customer.displayName)
}

🟦 Open CheckoutScreen.kt:42 from the failed Kotlin task. Inspect the Customer? source, intended absent/loading/error state, and the expression's required type. A safe call with a deliberate fallback or an explicit validated branch may be correct; adding !! merely converts a compile-time warning about the contract into a possible crash.

The final task exception summarizes failure rather than identifying its cause. Fix the nullable-state contract, rerun that variant's compilation, and test the empty/customer-present cases that motivated it. If a generated type caused cascades, inspect its earlier generator failure first. Kotlin null-safety contracts.

STUDIO-02 — Answer

Short answer: The terminal and Android Studio may run Gradle with different Java runtimes or configuration. Compare the actual Gradle JDK, wrapper, plugins, selected variant, and dependency setup before changing source code. An unresolved class can also come from the wrong module or dependency scope rather than a broken IDE.

Detailed explanation:

Illustrative diagnostic sequence in the affected project; compare the runtime printed by the wrapper with Studio's configured Gradle JDK, then inspect the correct source set's compile graph.

BASH
./gradlew --version
./gradlew :app:compileDebugKotlin --stacktrace
./gradlew :app:dependencies --configuration debugCompileClasspath

These commands assume an app module/debug variant; they were not run for this lesson and do not change the project's chosen JDK.

Compare the JDK actually running the wrapper in each environment, Android Studio's Gradle JDK configuration, wrapper version, AGP/Kotlin plugins, environment selection, repositories, and selected variant. The IDE runtime and Gradle runtime can differ. Align to the project's supported toolchain; consult the pinned plugin's compatibility requirements instead of changing every version. JDK selection for Android builds.

For PaymentsClient, inspect its declaration/import, owning module, selected source set, generator outputs, visibility, and compile classpath. A dependency only in a test or runtime configuration is not necessarily available to main compilation. Re-run sync after a build-model change, then compile the relevant source set. A terminal build of another variant is not an equivalent comparison. Android dependency configurations.

STUDIO-03 — Answer

Short answer: Find both paths that supply the same class in the selected variant’s resolved dependencies. One library may already package a class also supplied by another dependency. Remove or replace the conflicting source deliberately; multidex and broad exclusions do not establish that the remaining dependency is correct.

Detailed explanation:

Use the actual variant's resolved runtime graph to find both paths; inspect whether one jar embeds/shades the same class as another dependency. Example:

BASH
./gradlew :app:dependencyInsight --dependency codec --configuration debugRuntimeClasspath

Choose compatible artifacts or remove the redundant ownership source. A narrow exclusion is justified only after confirming the remaining dependency supplies the needed contract; test its runtime paths. A bundled duplicate can require changing the producing library because excluding a transitive coordinate cannot remove classes physically embedded in its jar.

Multidex addresses method-reference capacity across dex files, not two definitions of the same class. For a different dex failure, read its own diagnostic; do not classify every dex error as duplication. Gradle dependency insight, Android multidex purpose.

STUDIO-04 — Answer

Short answer: A resource-linking error means a referenced resource cannot be resolved for that build, so inspect its name and selected source sets. A manifest-merger conflict means two manifests disagree on a value. Use the merger report to identify both sources and choose the intended policy before overriding anything.

Detailed explanation:

Illustrative resource correction in the owning module's default res/values/strings.xml; keep locale overrides separate and verify the selected variant includes this source.

XML
<resources>
    <string name="pay_now">Pay now</string>
</resources>

This fixes the missing symbol from the exercise. The manifest conflict still needs an independent policy/provenance decision.

The first error belongs to resource linking: check the referenced string's name, namespace, resource dependency, and availability in the selected source sets. Fix the source resource/reference; do not edit generated R output. AAPT2 compile/link phases.

The second belongs to manifest merging. Open the app's Merged Manifest view and inspect which manifest contributes each conflicting attribute. Resolve the intended behavior at the correct app/variant boundary. Use a targeted merge marker only when the app intentionally owns that decision and you understand the library requirement. Blind replacement can change backup/privacy behavior or hide a broken integration. Verify the packaged variant's merged result and affected behavior. Manifest merge provenance and markers.

STUDIO-05 — Answer

Short answer: No. A keep rule cannot provide a class missing from the dependencies. First distinguish an absent dependency from a member removed or renamed during shrinking, especially when reflection is involved. Use the mapping file for that exact release to recover useful names from an obfuscated crash trace.

Detailed explanation:

🟥 A keep rule cannot create an absent class. For a build-time missing type, inspect the dependency graph, API compatibility, and whether the reference is required or genuinely optional. Review generated suggestions where available; broad dontwarn suppression can conceal a real missing runtime requirement.

A release-only reflective lookup may need a precise rule preserving the required member/name/attributes, or a code-generation/static-reference alternative. Reproduce with the exact minification/dependency setup, inspect the merged rules, and test the reflective entry point in that build. Keeping every class disables useful optimization without proving the contract correct. R8 optimization troubleshooting, keep-rule contracts.

Archive the mapping with its release artifact/version. Retrace with that exact mapping; another build's mapping can mislead. Example command, when the SDK retrace tool is on the path:

BASH
retrace mapping.txt crash.txt

Check cause chains and app frames after reconstruction; native crashes need their own matching symbols. R8 retrace.

STUDIO-06 — Answer

Short answer: Yes. Evaluating an expression runs code, so calling submitOrder can start another real submission. Even getters, watches, and breakpoint conditions can have effects or change timing. Inspect stable state and use isolated test data rather than invoking a business action simply to observe it.

Detailed explanation:

Illustrative breakpoint setup, expressed as a human-readable checklist rather than an importable settings format. The condition/watch are pure app-state reads.

TEXT
Location: submit intent handler, before enqueueing work
Condition: operationId == debugOperationId
Suspend: Thread, if offered for this debugger/breakpoint
Watch: pendingOperationId
Exception breakpoint: IllegalStateException, relevant app filter
Logging alternative: Suspend off; log operation generation only
Never evaluate: submitOrder(), retryPayment(), or a mutating getter

🟥 Evaluate Expression executes code. submitOrder() may enqueue work or submit a real order; getters, toString(), watches, and breakpoint conditions can also run code and alter timing. Inspect stable scalar IDs/state instead, and use isolated test data for debugging. Android debugger operations.

Condition a breakpoint on a known request/operation ID or a pure flag such as an already-pending state. An exception breakpoint can stop on the specific relevant thrown exception; distinguish caught from uncaught exceptions to reduce noise. Choose thread/all-thread suspension deliberately: pausing one thread can leave others running, while pausing all perturbs scheduling more broadly. Record handler entry and operation identity without secrets, then verify deduplication in a test rather than deliberately invoking a side effect from the debugger. Prefer small read-only observations; debugger behavior is not a production execution schedule.

STUDIO-07 — Answer

Short answer: Begin at the application frame nearest the underlying cause: the quantity mapper that tries to parse an empty string. Trace where that input came from and what the boundary promises to accept. Catching a broad exception around rendering hides the symptom without fixing the invalid input or its handling.

Detailed explanation:

Illustrative boundary correction: parse once, enforce the domain's positive-quantity rule, and present validation feedback without crashing the renderer.

KOTLIN
fun parseQuantity(raw: String): Int? =
    raw.trim().toIntOrNull()?.takeIf { it > 0 }
​
fun onQuantitySubmitted(raw: String) {
    val quantity = parseQuantity(raw)
        ?: return showQuantityError("Enter a positive whole number")
    updateDraftQuantity(quantity)
}

The two UI/model callbacks are app dependencies; add any real product upper bound explicitly.

Start with the cause's app frame, CheckoutMapper.quantity:21, then inspect the caller's contract and raw input origin. Set a NumberFormatException breakpoint for the reproducing flow, with suitable filters if the library throws many expected exceptions. Check whether empty means missing, invalid input, or a mapping bug; verify locale/range/domain constraints as applicable.

Handle invalid input at the parsing/domain boundary, for example with toIntOrNull() followed by explicit validation and a typed error. An outer blanket catch can hide a violated invariant, render inconsistent state, or misclassify programmer bugs as network failures. Add empty/invalid/valid tests. Keep timestamp/process/build identity because a neighboring log line may belong to another process or run. Logcat exception context.

STUDIO-08 — Answer

Short answer: A successful response is only one step between the server and the UI. Follow the same request and account through response parsing, the database write, observation, and final state publication to find where the newer value is lost. An empty inspector view may mean the network client is unsupported, not that no request happened.

Detailed explanation:

Illustrative read-only Database Inspector queries for a hypothetical account-scoped note/outbox schema; bind or safely substitute test identifiers using the inspector's supported query workflow.

SQL
SELECT note_id, server_version, sync_state
FROM notes
WHERE account_id = :account_id AND note_id = :note_id;
​
SELECT operation_id, base_version, retry_count, acknowledged
FROM pending_edits
WHERE account_id = :account_id AND note_id = :note_id;

Match these fields to the actual schema, and correlate the version with a redacted network request ID; neither query mutates the reproduction.

Correlate one request ID and selected account with request parameters, response status/version, and completion time. Then inspect the corresponding local row/version and transaction result. If the row is fresh, trace the observed query's filters and the mapper/state publication; check mutable in-place updates, equality conflation, stale requests, and lifecycle collection. If the row is stale, inspect write rejection, conflict policy, transaction rollback, and account scoping.

Use read-only inspector queries first; editing rows can destroy the reproduction. An unsupported networking client may be invisible to Network Inspector even while requests succeed. Add explicit safe boundary telemetry or a supported test adapter; do not disable TLS validation just to see traffic. Database Inspector capabilities, Network Inspector supported libraries.

STUDIO-09 — Answer

Short answer: No. Recomposition means Compose is reconsidering part of the UI; a count alone does not show expensive work or missed frames. Use layout and state inspection for correctness, and a frame trace for visible performance. Selection moving to another row is a separate identity problem that needs stable item keys.

Detailed explanation:

Illustrative row correction: selection follows stable task identity and is owned above the row; TaskRow and the selection callback belong to the app.

KOTLIN
LazyColumn {
    items(tasks, key = { it.id }) { task ->
        TaskRow(
            task = task,
            selected = task.id in selectedIds,
            onSelectedChange = { selected ->
                onSelectionChanged(task.id, selected)
            }
        )
    }
}

A count is a clue, not proof of expensive work. Use Layout Inspector to identify the actual node, parameters/bounds, and recomposition/skip behavior for one reproducible interaction. Distinguish unnecessary expensive derivation from cheap expected recomposition; confirm user-visible frame cost with a trace. Layout Inspector.

Selection moving after insertion is a separate identity/state-ownership defect. Use stable unique item keys and an appropriate owner for selection; check that observable state changes, rather than mutating an ordinary list invisibly. Reorder/insert tests establish correctness. Bounds inspection helps clipping/touch-target questions; frame traces locate the timing cost. Neither a stable key nor a reduced count alone proves performance improved. Android questionnaire: Compose identity.

STUDIO-10 — Answer

Short answer: Starting a coroutine does not automatically move its work away from the main thread. Thread.sleep and a blocking cache read stop that thread from processing the UI. A suspending delay lets the thread do other work, while genuinely blocking operations need an appropriate dispatcher boundary.

Detailed explanation:

Illustrative main-safe repository boundary: dispatch the actual blocking read, not the entire UI lifecycle. The dispatcher and reader are injected app dependencies.

KOTLIN
class ReportRepository(
    private val io: CoroutineDispatcher,
    private val reader: BlockingReportReader
) {
    suspend fun readCachedReport(): Report = withContext(io) {
        reader.read()
    }
}

The reader still needs its own cancellation/resource contract; no synthetic delay belongs in the production read path.

🟥 viewModelScope.launch does not automatically offload blocking work. On main, both Thread.sleep and the blocking cache read prevent UI processing. Use a short system trace around the interaction, inspect main's sleeping/blocking and IO boundaries, and verify with code/call stacks. Replace a simulated wait with delay; make the actual blocking repository operation main-safe with an injected appropriate dispatcher and cancellation/resource policy. CPU-heavy transformation usually needs a CPU-oriented dispatcher. Android coroutine main-safety guidance.

Low average CPU does not exclude a blocked main thread; aggregate usage hides per-thread waits and short critical stalls. A three-second freeze is harmful but this snippet alone does not prove an ANR occurred: system timeout conditions and context matter. Android ANR causes.

STUDIO-11 — Answer

Short answer: CPU samples reveal code that is actively computing, while thread states and lock ownership help explain blocked work. A suspended asynchronous call can leave the main thread free even when the request takes a long time. Diagnose which kind of waiting is happening before deciding where to move the work.

Detailed explanation:

Illustrative diagnosis worksheet, not recorded trace output: the three cases have the same wall duration but different causes.

TEXT
A: main Running -> parse call stack -> inspect CPU self time
B: main Blocked -> monitor owner -> inspect worker holding lock
C: request suspended -> main handles input -> inspect HTTP completion
Mutex wait: coroutine suspended -> inspect logical lock owner/generation
For every case: correlate the same request interval and thread tracks.

Only an actual capture can establish which of these patterns the application exhibits.

For A, CPU samples/self time and main-thread slices can identify parsing; reduce redundant work or move main-safe transformation outside the critical UI path. For B, inspect thread states, the main stack, lock owner, and worker activity; fix shared-lock scope or dependency direction rather than merely moving the waiter. For C, an asynchronous suspension can free main to process UI; correlate network timing and the request's owner/cancellation before treating it as a freeze.

A coroutine mutex waiter suspends, so it may consume little CPU while waiting indefinitely. Capture logical operation IDs and lock ownership boundaries; inspect recursive acquisition or a stalled owner. Waiting time is not necessarily CPU computation time. Sparse samples or a stack taken after recovery cannot exclude an earlier block. System-thread correlation, Kotlin non-reentrant mutex.

STUDIO-12 — Answer

Short answer: No. Rendering bars show stages of the framework’s rendering work and can include waits; a spike does not identify shader cost. Correlate the late frame with a system trace before choosing a GPU-specific investigation. Missing graphics data may reflect device or tool limitations rather than an idle GPU.

Detailed explanation:

Illustrative framework-frame capture command for the test package; this produces frame statistics, not GPU utilization or shader counters.

BASH
adb shell dumpsys gfxinfo com.example.app framestats

Replace the package with the installed test app, reproduce one delimited scroll journey, and correlate its frame interval with a supported system trace. AGI frame capture is a separate validated graphics workflow.

🟨 HWUI bars characterize CPU-side framework-rendering stages, including command-submission waits; a spike does not identify shader cost. Capture a short System Trace and correlate the specific late frame with main, RenderThread, scheduling, and any supported graphics-completion tracks. A CPU sample may miss short repeated work or mostly-waiting intervals. Rendering-bar interpretation.

If the rendering path and evidence justify graphics analysis, validate AGI support before frame capture: supported physical device/driver, required Android version, adb access, app configuration, and graphics API path. AGI's documented frame-profiling support covers supported Vulkan/OpenGL ES scenarios; it is not guaranteed for every device or Compose workflow. Inspect relevant captured commands/counters and correlate with the journey. Missing counters/tracks are unknown evidence, not zero GPU load. CPU utilization cannot prove GPU saturation, and GPU utilization cannot identify main-thread work. AGI frame profiling, device/app validation.

STUDIO-13 — Answer

Short answer: No. Higher display refresh rates allow less time between frames, so a 12-millisecond interval can fit the rough 60 Hz budget but exceed the 90 Hz or 120 Hz budget. First establish whether the measurement describes CPU work, GPU work, or actual presentation. Judge smoothness from delivered frames, not one average.

Detailed explanation:

Illustrative arithmetic only: compute nominal display intervals without presenting them as measured app performance.

KOTLIN
val illustrativeFrameMs = 12.0
for (refreshHz in listOf(60, 90, 120)) {
    val intervalMs = 1000.0 / refreshHz
    val exceedsNominalInterval = illustrativeFrameMs > intervalMs
    println("$refreshHz Hz: $intervalMs ms; exceeds=$exceedsNominalInterval")
}

Actual deadline compliance needs presentation/frame timing; this calculation cannot identify the limiting pipeline stage.

🧠 A 12 ms interval is below 16.67 ms at 60 Hz, but exceeds 11.11 ms at 90 Hz and 8.33 ms at 120 Hz. Even at 60 Hz it does not independently prove smoothness: define whether “12 ms” describes CPU work, GPU execution, a mean, or actual presentation. Tail delays, queueing, missed start times, and frame pacing matter.

CPU/GPU stages overlap across frames, so simply adding their durations or comparing an average to one nominal interval can misrepresent deadlines. Inspect actual frame timing/presentation and the work linked to late frames on the device's active refresh mode. Compare late-frame rate/distribution and interaction latency on the same workload, not just FPS or a best sample. These figures are arithmetic examples, not measurements. Android Studio frame/jank analysis.

STUDIO-14 — Answer

Short answer: Find a path from a live process object to the Activity that should have been released. A long-lived subscription may retain its callback, which in turn retains the Activity. Repeat the same navigation and cleanup sequence, then check that obsolete instances and their retaining paths disappear after the fix.

Detailed explanation:

Illustrative repair when the subscription is useful only while visible: retain the callback identity and pair registration with removal.

KOTLIN
class DetailsActivity : ComponentActivity() {
    private val onUpdate: () -> Unit = { title = "Updated" }
    override fun onStart() {
        super.onStart()
        Subscriptions.add(onUpdate)
    }
    override fun onStop() {
        Subscriptions.remove(onUpdate)
        super.onStop()
    }
}

This assumes the app's Subscriptions API removes that identical callback and delivers UI updates on main.

🟥 Process root → Subscriptions → callback → DetailsActivity keeps the obsolete screen reachable. Repeat enter → subscribe → leave cycles, return to a consistent idle point, and inspect retained Activity instances plus paths to GC roots in a heap dump. Confirm they represent destroyed screens rather than a currently visible screen or an intentionally retained owner. GC only reclaims unreachable objects; a reachable cycle remains live.

Store the registration token or identical callback and unregister at the matching lifecycle boundary; for visible observation, pair start/stop, and for Fragment UI use the view lifecycle. Cancel owned asynchronous work as needed. Repeat the same sequence after the fix and inspect whether obsolete instances/retaining paths disappear. A forced GC is a diagnostic aid, not a fix, and the dump itself perturbs memory. Heap-dump analysis, Android lifecycle-scoped work.

STUDIO-15 — Answer

Short answer: The managed heap contains only part of the process’s memory. Native allocations, bitmap backing storage, graphics buffers, and caches can grow independently of Kotlin object counts. Compare memory categories across repeated visits and investigate the growing category instead of treating one managed heap dump as proof that no leak exists.

Detailed explanation:

Illustrative byte-bounded bitmap cache; choose the budget from the app/device requirements, and inspect native/graphics ownership separately.

KOTLIN
class BitmapCache(maxBytes: Int) : LruCache<String, Bitmap>(maxBytes) {
    init { require(maxBytes > 0) }
    override fun sizeOf(key: String, value: Bitmap): Int =
        value.allocationByteCount
}
​
val cache = BitmapCache(configuredImageCacheBytes)
cache.put(imageKey, decodedBitmap)

The supplied budget/key/bitmap are app inputs. Eviction drops the cache reference; it must not recycle a bitmap that another consumer still uses.

Managed heap is only part of process memory. Inspect process/category trends, bitmap dimensions/lifetime, native allocation remaining size/call stacks, and graphics resources with the tools supported by that device. Native allocation profiling attributes tracked allocations, not every mapped file, driver buffer, or total graphics footprint. A managed wrapper may retain native backing storage; exact accounting varies by platform/resource.

Compare equivalent steady states after repeated navigation and distinguish a bounded reusable image cache from unbounded growth. Look for unnecessary full-resolution decoding, duplicate caches, and native/JNI ownership that lacks release. Size images for the display target and define cache limits/invalidation; do not arbitrarily recycle a bitmap still in use. Confirm both retention and peak memory during loading. Native allocation recording, Android native-memory investigation.

STUDIO-16 — Answer

Short answer: Yes. Detailed allocation recording adds observation work and can change the timing you are trying to measure. Use it to find allocation locations, then compare the same journey with lower-overhead recording and an unattached timing run. Keep build identity, device, and data comparable so the profiling session is not mistaken for normal performance.

Detailed explanation:

Illustrative comparison contract, with no fabricated results. A timing comparison keeps all named conditions equal; diagnostic captures answer allocation ownership separately.

YAML
timing_comparison:
  build: same release-like profileable configuration
  device: same physical model and OS
  journey: same image list and scroll sequence
  cache_policy: separate documented cold and warm runs
  profiler_mode: same low-overhead recording mode
allocation_diagnosis:
  build: debuggable
  recording: compare full with sampled; attribute creation stacks

Full allocation recording can introduce substantial observer overhead. Keep that debuggable session for locating allocation stacks, then compare sampled recording and an unattached/low-overhead timing run with the same journey. It may expose real churn, amplify it, or both. Recording mode must be part of the reported result. Java/Kotlin allocation modes.

Use the build/visibility required by the diagnostic task; heap and managed-allocation capture require debuggable access in the documented Profiler workflow. For representative timing, use release-like profileable settings and the target hardware, preserving artifact identity, R8 mapping, and relevant native symbols for interpretation. Keep optimization and compilation/profile warmup comparable, control thermal/network/cache conditions, and repeat enough to see variation. Never compare one debug instrumented run to one optimized release run as proof of a code change's benefit. Profiler build variants.

STUDIO-17 — Answer

Short answer: A breakpoint changes timing and can prevent the completion order that exposes the bug. Running state access on main still permits an older suspended request to finish after a newer one. Use controlled request completions and a current-request check to prove correctness without depending on debugger timing.

Detailed explanation:

Illustrative regression test using an app-specific controllable fake and construction helper. Both requests are started before their completions are released; the fake permits obsolete responses deliberately.

KOTLIN
@Test fun olderCompletionCannotReplaceNewerResults() = runTest {
    val fake = ControlledSearchRepository()
    val model = makeSearchModel(fake, backgroundScope)
    model.search("ca")
    runCurrent()
    model.search("cat")
    runCurrent()
    fake.complete("cat", listOf("cat"))
    runCurrent()
    fake.complete("ca", listOf("car"))
    runCurrent()
    assertEquals(listOf("cat"), model.results.value)
}

🟥 Main confinement prevents simultaneous state access, but a suspended older request can resume after the newer request. Breakpoints alter completion order and can hide that logical race. Record request generation, query identity, start/completion/publication, and cancellation status without exposing private search content.

Cancel obsolete work and revalidate a generation/request ID before publishing; latest-only flow operators can also express the policy when the repository honors cancellation. A mutex around only the state assignment does not identify which result is current. For shared counters on multiple threads, an atomic update or a consistently owned critical section addresses a different lost-update problem.

Use runTest with one shared test scheduler and a fake whose completions are explicitly controlled: hold A, complete B, then complete A; assert B remains visible and no stale error appears. Virtual time verifies chosen interleavings, not all real thread contention. Add focused real-parallel invariant tests where shared-memory risk exists. Android coroutine tests, stale-response correction.

STUDIO-18 — Answer

Short answer: Show the affected user journey, a reproducible baseline, and an improvement on representative devices using the same measurement. The fix should address a supported cause and include a regression check, a rollout owner, and a way to limit exposure if it fails. Moving work to IO or increasing memory limits is not evidence by itself.

Detailed explanation:

Illustrative development-only main-thread policy; initialize it on the main thread. penaltyLog reports selected accidental IO rather than inventing a performance benchmark.

KOTLIN
if (BuildConfig.DEBUG) {
    StrictMode.setThreadPolicy(
        StrictMode.ThreadPolicy.Builder()
            .detectDiskReads()
            .detectDiskWrites()
            .detectNetwork()
            .penaltyLog()
            .build()
    )
}

This is one diagnostic signal; acceptance still needs the comparable capture and release checks described below.

Define the affected journey, severity, reproduction, build identity, and baseline before assigning a fix. Capture one relevant CPU/system trace and memory sequence; add graphics detail only when evidence supports that hypothesis. Use representative devices/refresh modes and record profiler mode, cache/network conditions, and thermal state. Assign a specific owner and bounded change to each established cause.

An optional development-only StrictMode policy can expose accidental main-thread disk/network access and selected resource leaks. It does not detect every expensive CPU operation, logical race, native leak, or rendering defect, and a clean run is not a performance certificate. Use log/report behavior appropriate for development; do not ship unexplained failure penalties. StrictMode.

Require a regression test for correctness, comparable before/after captures for the measured symptom, and release-like journey checks. Set acceptance thresholds from actual product budgets/baseline; never invent improvement percentages. Preserve mappings/artifacts, stage rollout, and monitor crash/ANR/frame/memory-related signals by version/device cohort using privacy-safe telemetry. Plan a rollout pause, feature disablement, or hotfix because replacing every installed mobile binary is not instantaneous. Increasing heap allowance or moving every operation to IO without diagnosis can mask retention and create new scheduling problems. Incident and release leadership.

Key Takeaways

  • Build output diagnoses build stages; Logcat/debugger investigate runtime behavior; inspectors follow persisted/network/UI state; profilers explain measured cost and ownership.
  • Follow a concrete task error, causal stack, retaining path, or frame interval. Generic failure summaries and aggregate resource percentages are starting points.
  • CPU, GPU, waiting, allocation, and retention answer different questions. Match device/tool support and capture overhead to the claim.
  • A useful fix preserves behavior, has focused regression evidence, and improves the affected journey under a comparable measurement setup.