Skip to content
Commitwise
Menu
Android Development

ANRs, crashes and debugging in production

Read Android crash reports and deobfuscate them with R8 mapping files, understand what causes ANRs and how to read their traces, find out why the app was killed with ApplicationExitInfo, catch problems early with StrictMode, and keep Android vitals under Google Play's bad-behavior thresholds.

advanced

The core idea with one simple example.Step by step, with more examples and exercises.A cheat sheet: key APIs, gotchas and trade-offs.Internals, trade-offs and production pitfalls.

Google Play sends a warning: the app’s user-perceived ANR rate is 0.6%, above the 0.47% threshold, and the store may show it lower in search results. The top ANR has a main thread “waiting to lock” something. The top crash is java.lang.NullPointerException at a.b.c.d(SourceFile:3), unreadable. And support tickets say the app “restarts by itself” on older phones, with nothing in the crash reports at all.

Android apps fail in three different ways: crashes (an exception nobody caught), ANRs (Application Not Responding: the main thread was blocked too long), and process deaths the user notices but no crash report records. This lesson shows how to read each one, the usual causes, and the tools that find them before users do.

New to some of these? Open what you need, or skip ahead.

Basics:What is the main thread?

On Android, the main thread (or UI thread) draws the screen and handles touches. Everything that takes time, like network calls, database queries or big file reads, must run elsewhere (coroutines on Dispatchers.IO, WorkManager). If the main thread is busy, the app freezes. See the Coroutines and Flow lesson.

Basics:What is R8?

R8 shrinks and obfuscates release builds: it removes unused code and renames classes and methods to short names like a.b.c. That makes the app smaller, but stack traces from release builds become unreadable without the mapping file that R8 writes for each build. See r8R8The Android build tool that shrinks, obfuscates and optimizes release builds.Open in glossary → and Google Play release and R8.

Part Not started

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)
  • getHistoricalProcessExitReasons returns 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.
Spot the bugA screen that sometimes freezes on open

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) }
    }
}

Practice: read a crash report

  1. Find the exception and message: java.lang.IllegalStateException: ViewModel cleared or NullPointerException: … on a null object reference.
  2. 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.
  3. Find your first frame: the topmost line from your package. That’s where to start reading code.
  4. 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.
  5. 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?

Common ANR causes

CauseTypical traceFix
Disk or network on the main threadSQLiteConnection, FileInputStream, SocketInputStream in mainMove to Dispatchers.IO/WorkManager; StrictMode in debug
Lock contentionmain Blocked, waiting to lock held by a worker doing I/ONever hold locks across I/O; use Mutex/actors; narrow critical sections
SharedPreferences.apply() backlogmain in QueuedWork.waitToFinish during onPause/onStopFewer, batched writes; move to DataStore
Slow onReceivemain in a receivergoAsync() with a short job, or WorkManager
Binder calls to the system or other appsmain in BinderProxy.transactCache results, call off the main thread
Heavy startupmain in Application.onCreate, content providersLazy init, App Startup library, baseline profiles
  • Crashes: JVM traces + R8 mapping.txt per 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

  1. What causes an ANR?

  2. A release crash shows names like a.b.c.d. What's needed to read it?

  3. How can an app learn it was killed for low memory last time?

  4. An ANR trace shows main Blocked, waiting to lock an object held by a worker in socketRead. Fix?

Crashes are uncaught exceptions (Java/Kotlin stack traces, deobfuscated with the build's R8 mapping file) or native crashes (tombstones). An ANR happens when the main thread can't handle input within 5 seconds (or a broadcast or service runs too long); the report includes all threads' stacks. Low-memory kills leave no report: ApplicationExitInfo (API 30+) explains past exits. Play's Android vitals thresholds are 1.09% for crashes and 0.47% for ANRs.

Part Not started

Finding the causes

Most ANRs and many crashes can be caught before release with the right tools:

  • StrictMode watches the main thread in debug builds and complains (in Logcat, or by crashing on purpose) when it touches the disk or the network.
  • LeakCanary finds memory leaks automatically during development: a screen that stays in memory after it was closed, which eventually leads to out-of-memory crashes.
  • The Android Studio profilers and Perfetto show what each thread was doing over time, so you can see exactly what blocked the main thread.

For problems that only happen in production:

  • Breadcrumbs: log what the user did before a crash (Crashlytics.log("Opened cart with 3 items")) and attach custom keys (screen, experiment, account type).
  • Staged rollouts: release to 5% of users first. If a new crash or ANR appears, halt the rollout in Play Console.
  • Kill switches: a remote config flag that turns off a risky feature without a new release.

Shift detection left: StrictMode thread policies (detectDiskReads/Writes, detectNetwork, detectCustomSlowCalls, detectUnbufferedIo) and VM policies (detectLeakedClosableObjects, detectActivityLeaks, detectNonSdkApiUsage) in debug and internal builds, with penaltyDeath on CI test runs so violations fail tests; LeakCanary in debug; Macrobenchmark and baseline profiles for startup and jank. Reproduce with Perfetto system traces (main thread slices, binder transactions, lock contention, CPU scheduling) and Android Studio’s CPU, memory and energy profilers. In production, combine Play vitals (including ANR clusters and their stacks), Crashlytics or Sentry with breadcrumbs and keys, and your own ApplicationExitInfo telemetry for LMK and ANR context. Release with staged rollouts, monitor crash-free users and ANR rate per version during the first hours, halt on regressions, and keep remote kill switches for risky features. Investigate by version, device model (OEM-specific ANRs and crashes are common), Android version and memory class.

class ShopApp : Application() {
    override fun onCreate() {
        super.onCreate()
        if (BuildConfig.DEBUG) {
            StrictMode.setThreadPolicy(
                StrictMode.ThreadPolicy.Builder()
                    .detectDiskReads()
                    .detectDiskWrites()
                    .detectNetwork()                       // also caught by NetworkOnMainThreadException in release
                    .detectCustomSlowCalls()
                    .penaltyLog()
                    .penaltyFlashScreen()                  // a red flash: hard to ignore during development
                    .build()
            )
            StrictMode.setVmPolicy(
                StrictMode.VmPolicy.Builder()
                    .detectLeakedClosableObjects()         // cursors and streams that were never closed
                    .detectActivityLeaks()
                    .penaltyLog()
                    .build()
            )
        }
    }
}
  • In debug builds only, StrictMode watches for disk reads and writes and network calls on the main thread, and flashes the screen red when one happens.
  • The VM policy reports cursors and streams that were never closed, and activities that stay in memory after they’re destroyed.
  • In release builds it’s off, so users never see it.

Predict the output

A settings screen saves 40 preferences with SharedPreferences.apply() each time the user leaves it (in onStop). On a slow phone, users get ANRs when leaving the screen, with the main thread in QueuedWork.waitToFinish. Why, if apply() is asynchronous?

Production puzzles

Spot the bugA cache that freezes the UI

Tap the line with the bug.

class CartRepository(private val api: CartApi) {
    private val lock = Any()
    private var cached: List<CartItem> = emptyList()

    fun items(): List<CartItem> = synchronized(lock) { cached }      // called from the UI

    suspend fun sync() = withContext(Dispatchers.IO) {
        synchronized(lock) {
            cached = api.fetchCart()                                   // blocking HTTP call
        }
    }
}

Exercisehard

Bring the ANR rate under the threshold

Android vitals: ANR rate 0.62% (threshold 0.47%). The top clusters are: (1) main thread in SQLiteDatabase.query from Application.onCreate, (2) QueuedWork.waitToFinish in onStop, (3) a BroadcastReceiver for connectivity changes doing a sync, (4) a long tail on two OEM device models. Plan the work for the next two releases.

›

Rank by share of ANRs and by cost of the fix; decide what you can measure locally before shipping.

SolutionTry it yourself first
  1. Startup query (largest, cheap): move the query off the main thread (lazy loading through a repository on Dispatchers.IO), use the App Startup library or lazy initialization for SDKs, and verify with a Macrobenchmark startup test.
  2. SharedPreferences backlog: batch writes into one edit() and migrate the hot settings to DataStore.
  3. Receiver: replace the manifest connectivity receiver with a WorkManager job using a network constraint; never sync in onReceive.
  4. OEM tail: reproduce on those models (device lab or Firebase Test Lab), check for vendor-specific binder or WebView issues, and add ApplicationExitInfo telemetry to get full traces from the field.
  5. Guardrails: StrictMode with penaltyDeath in CI instrumented tests, ANR rate per version in the release checklist, staged rollout halted if the new version’s ANR rate rises.
Exercisemedium

Find the leak

LeakCanary reports that CheckoutActivity is retained after it was closed, through PaymentSdk.listener. What’s probably wrong, and how would you fix it?

›

Who keeps a reference to the activity after onDestroy?

SolutionTry it yourself first

The activity registered itself (or an inner class that references it) as a listener in a singleton SDK and never unregistered. The SDK lives as long as the process, so it keeps the activity, its views and everything they reference in memory.

  • Unregister in the matching lifecycle callback (onDestroy, or better, use a lifecycle-aware observer that unregisters itself).
  • Prefer registering from a ViewModel or a lifecycle-scoped component, not from the activity.
  • Never pass an Activity context to long-lived objects; use applicationContext when a context is needed.
  • StrictMode thread and VM policies in debug and internal builds, penaltyDeath in CI; LeakCanary in debug.
  • Perfetto and profilers for main-thread slices, binder calls and lock contention; Macrobenchmark for startup and jank.
  • Never hold locks across I/O; SharedPreferences.apply() backlogs block onPause/onStop; receivers delegate to WorkManager.
  • Production: Play vitals clusters, Crashlytics breadcrumbs and keys, ApplicationExitInfo telemetry; staged rollouts with halts; remote kill switches; slice by OEM and Android version.

Check this part

  1. What does StrictMode do in a debug build?

  2. A new release shows a crash cluster on day one of a 5% staged rollout. First step?

  3. Why can SharedPreferences.apply() cause ANRs?

  4. Where should a connectivity-change sync run?

Turn on StrictMode in debug builds to catch disk and network access on the main thread and leaked resources. Reproduce ANRs and jank with Perfetto and the Android Studio profilers, find leaks with LeakCanary, and add breadcrumbs and custom keys to crash reports. Ship behind staged rollouts with a remote kill switch, and halt a rollout when a new crash or ANR cluster appears.

Key takeaways

  • Crashes are uncaught exceptions; upload R8 mapping files to read release traces.
  • ANRs mean the main thread was blocked for about 5 seconds: no disk, network or long locks there.
  • Low-memory kills leave no crash report; ApplicationExitInfo tells you why the app died.
  • StrictMode and LeakCanary catch problems before release; staged rollouts limit the damage after.
  • Read ANR traces across all threads; the main thread often waits indirectly (locks, binder, QueuedWork).
  • Collect exit reasons and traces from the field; slice by version, OEM and Android version.
  • Keep vitals under Play’s thresholds with CI guardrails, staged rollouts and kill switches.
  • Fix causes (I/O off main, no locks across I/O, lazy startup), and prove them with benchmarks.

Finished this page?Nice work, this page is complete!

Mark it as done to track your progress. It's saved in this browser, no account needed.

Its cards are now in your Bites review ⚡
Esc

Type to search the whole site.