Crashes, ANRs and silent deaths
A crash is an exception that nothing caught: a NullPointerException, an IllegalStateException, an index out of bounds. Android shows “App keeps stopping” and the report contains a stack trace: the chain of method calls, newest first. In release builds the names are obfuscated by R8, so you need the build’s mapping file to turn a.b.c.d back into CheckoutViewModel.total. Google Play and Crashlytics do it automatically when the mapping file is uploaded.
An ANRANR (Application Not Responding)An Android error raised when the main thread is blocked too long, typically when input isn't handled within 5 seconds.Open in glossary → (“Application Not Responding”) happens when the main thread is blocked: the user taps, and the app can’t respond within 5 seconds. Android shows a dialog offering to close the app. The ANR report contains the stack of every thread at that moment, so you can see what the main thread was waiting for.
A silent death happens when Android kills the app’s process, most often because the phone ran out of memory. There’s no crash report; the user just sees the app restart. Since Android 11, the app can ask the system why it was killed last time.
Google Play tracks crash and ANR rates in Android vitals. Above 1.09% of daily users with a crash, or 0.47% with an ANR, the app is considered to have “bad behavior” and can be shown less in the store.
JVM crashes produce stack traces; release builds need the R8 mapping.txt of that exact build (uploaded by the Gradle plugin to Play and Crashlytics, or retraced manually with retrace). Native crashes produce tombstones and need unstripped native libraries or symbol files. ANRs trigger when input dispatch times out (5 s), a foreground BroadcastReceiver.onReceive exceeds ~10 s, a service fails to start in time, or a foreground service isn’t promoted with startForeground in time; the trace dumps all threads, and the main thread’s state (BLOCKED waiting to lock, WAITING, in a binder call, in nativePollOnce meaning idle at the moment of the dump) tells the story. Process deaths without reports (low-memory kills, excessive resource use, user force-stops from settings, crashes in other processes) are visible through ActivityManager.getHistoricalProcessExitReasons() (ApplicationExitInfo, API 30+), including ANR traces via traceInputStream. Android vitals measures user-perceived rates per day: bad-behavior thresholds are 1.09% (crashes) and 0.47% (ANRs) overall, with stricter per-device thresholds (8%); exceeding them can reduce store visibility and add warnings on the listing.
// API 30+: call once at startup, e.g. from a background coroutine
fun reportPreviousExits(context: Context) {
val activityManager = context.getSystemService(ActivityManager::class.java)
val exits = activityManager.getHistoricalProcessExitReasons(context.packageName, 0, 5)
for (exit in exits) {
when (exit.reason) {
ApplicationExitInfo.REASON_ANR -> {
val trace = exit.traceInputStream?.bufferedReader()?.use { it.readText() }
telemetry.record("exit_anr", mapOf("description" to exit.description, "trace" to trace?.take(20_000)))
}
ApplicationExitInfo.REASON_LOW_MEMORY ->
telemetry.record("exit_low_memory", mapOf("pssKb" to exit.pss, "importance" to exit.importance))
ApplicationExitInfo.REASON_CRASH_NATIVE ->
telemetry.record("exit_native_crash", mapOf("description" to exit.description))
ApplicationExitInfo.REASON_EXCESSIVE_RESOURCE_USAGE ->
telemetry.record("exit_resources", mapOf("description" to exit.description))
}
}
}// The interesting part of an ANR trace: the main thread is waiting for a lock
"main" prio=5 tid=1 Blocked
at com.example.shop.cart.CartRepository.items(CartRepository.kt:41)
- waiting to lock <0x0a1b2c3d> (a java.lang.Object) held by thread 23
at com.example.shop.cart.CartViewModel.<init>(CartViewModel.kt:18)
...
"DefaultDispatcher-worker-3" prio=5 tid=23 Native
at java.net.SocketInputStream.socketRead0(Native method)
at com.example.shop.cart.CartRepository.sync(CartRepository.kt:77)
- locked <0x0a1b2c3d> (a java.lang.Object)getHistoricalProcessExitReasonsreturns the last few times the app’s process ended, with a reason: crash, ANR, low memory, killed by the user, and more.- For ANRs, it even includes the thread dump, so you can collect ANR traces with your own telemetry.
- The trace shows the main thread
Blocked, waiting for a lock that thread 23 holds, and thread 23 is in the middle of a network read while holding it. The main thread waits for the network, without ever calling it directly.
Tap the line with the bug.
class ProfileActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val profile = runBlocking { api.loadProfile() }
setContent { ProfileScreen(profile) }
}
}Hint: Which thread does runBlocking block, and what happens on a slow network?
runBlocking blocks the main thread until the network call finishes. On a fast connection the screen opens a bit late; on a slow one the user taps, nothing responds, and after 5 seconds the system reports an ANR. Coroutines don’t help when you block the thread that should be free.
Load in a ViewModel and let the screen show a loading state:
class ProfileViewModel(private val api: ProfileApi) : ViewModel() {
val state: StateFlow<ProfileState> = flow { emit(ProfileState.Loaded(api.loadProfile())) }
.catch { emit(ProfileState.Error) }
.stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), ProfileState.Loading)
}Practice: read a crash report
- Find the exception and message:
java.lang.IllegalStateException: ViewModel clearedorNullPointerException: … on a null object reference. - Check the mapping: if names look like
a.b.c, make sure the mapping file for that version was uploaded (Play Console → App bundle explorer, or Crashlytics), so the trace is readable. - Find your first frame: the topmost line from your package. That’s where to start reading code.
- Look at the context: Android version, device, app version, and breadcrumbs (Crashlytics logs). A crash only on Android 14 points to a behavior change in that version.
- Ask why the value was unexpected, reproduce it in a test, and fix the cause.
Predict the output
An ANR report's main thread is at android.os.MessageQueue.nativePollOnce, idle, waiting for messages. What does that tell you?
nativePollOnce means the main looper is waiting for the next message, i.e. idle. Traces are captured some time after the ANR is detected, so the culprit may have finished just before. Look at the other threads, the CPU usage section and what happened just before (breadcrumbs, Perfetto traces from a reproduction). Many 'idle main thread' ANRs come from broadcast receivers or services that took too long, not from the UI.
Common ANR causes
| Cause | Typical trace | Fix |
|---|---|---|
| Disk or network on the main thread | SQLiteConnection, FileInputStream, SocketInputStream in main | Move to Dispatchers.IO/WorkManager; StrictMode in debug |
| Lock contention | main Blocked, waiting to lock held by a worker doing I/O | Never hold locks across I/O; use Mutex/actors; narrow critical sections |
SharedPreferences.apply() backlog | main in QueuedWork.waitToFinish during onPause/onStop | Fewer, batched writes; move to DataStore |
Slow onReceive | main in a receiver | goAsync() with a short job, or WorkManager |
| Binder calls to the system or other apps | main in BinderProxy.transact | Cache results, call off the main thread |
| Heavy startup | main in Application.onCreate, content providers | Lazy init, App Startup library, baseline profiles |
- Crashes: JVM traces + R8
mapping.txtper build (upload via the Gradle plugin); native tombstones need symbols. - ANRs: input dispatch 5 s, foreground broadcasts ~10 s, service and foreground-service start deadlines; read the main thread state across all thread stacks.
- Silent deaths (LMK, excessive resources):
getHistoricalProcessExitReasons()/ApplicationExitInfo(API 30+), including ANR traces. - Android vitals bad-behavior thresholds: 1.09% user-perceived crashes, 0.47% ANRs (8% per device model); store visibility at stake.
Check this part
What causes an ANR?
A release crash shows names like a.b.c.d. What's needed to read it?
How can an app learn it was killed for low memory last time?
An ANR trace shows main Blocked, waiting to lock an object held by a worker in socketRead. Fix?