How do you investigate and fix ANRs in an Android app?
AndroidSenior
In shortStart from Android vitals clusters and full traces, read the main thread's state across all threads to find what it waited for, reproduce with StrictMode and Perfetto, and fix the cause: I/O off the main thread, no locks held across I/O, fast receivers, lean startup. Then guard against regressions.
Model answer
What triggers them: the main thread not handling input for ~5 s, a foreground broadcast receiver running ~10 s, or services and foreground services missing their start deadlines.
Where to look: Android vitals ANR clusters with stack traces, ApplicationExitInfo (API 30+) with REASON_ANR and traceInputStream for full traces in your own telemetry, and breadcrumbs from the crash reporter.
Reading the trace: check the main thread state. Blocked waiting to lock means another thread holds the lock (find it and see what it’s doing: often network or disk). Frames in SQLiteConnection, FileInputStream or SocketInputStream mean I/O on main. BinderProxy.transact means a slow call into the system or another process. nativePollOnce means main was idle at dump time: look at receivers, services and other threads.
Common causes and fixes:
- Disk or network on main → coroutines on
Dispatchers.IO, Room and DataStore off main. - Locks held during I/O → do I/O outside critical sections, publish results atomically (
StateFlow, atomic references). SharedPreferences.apply()backlogs awaited inonPause/onStop→ batch writes, DataStore.- Heavy
onReceive→goAsync()for short work or WorkManager. - Heavy startup in
Application.onCreateand content providers → lazy initialization, App Startup, baseline profiles.
Prevention: StrictMode in debug and CI, Macrobenchmark startup tests, ANR rate per version in the release checklist, staged rollouts with halts.
What they're looking for
What triggers ANRs, where traces come from (vitals, ApplicationExitInfo), reading thread states, the common causes including indirect ones, the tools, concrete fixes and prevention.
Common mistakes
- Only looking for code that runs on the main thread directly.
- Assuming nativePollOnce on main means the main thread was the culprit.
- Raising timeouts or catching exceptions instead of fixing the cause.
More android questions
- How do you make sure background work in a mobile app stops when the user leaves the screen?Mid-level
- What's the difference between a configuration change and process death on Android, and what survives each?Mid-level
- How would you modularize a large Android app, and how do you keep builds fast?Senior
- How do you store an auth token securely on Android?Mid-level