ANRs: causes and fixes
Why it matters
- ANRs (Application Not Responding) are one of the main reliability problems Google Play tracks in Android vitals, next to crashes. A high user-perceived ANR rate can reduce your app's visibility on Play.
- Interviewers use ANR debugging to test whether you understand the main-thread contract, coroutine dispatchers, and how to read a thread dump.
- When the main thread is blocked, the app freezes and then shows the "App isn't responding" dialog. Unlike a crash, there is no stack trace in your own logs, so you need to know where ANR traces live.
- ANR fixes overlap with jank and startup work in this module: the same discipline (keep I/O and heavy work off the main thread, avoid lock contention) helps all three.
The simple explanation
- The main thread is a single-lane road: one stalled car blocks every car behind it, including your taps.
- The system is the traffic officer: if a car has not moved after a fixed time (5 s for input), it declares an ANR.
- Moving work to a background dispatcher sends the slow truck to a side road so traffic keeps flowing.
- StrictMode is a speed camera in debug builds: it flags every time the main thread touches the disk or network.
- An ANR trace is the dash-cam footage: it shows the main thread's stack, and every other thread's, at the moment of the ANR.
What causes an ANR in Android? An ANR happens when the app's main (UI) thread is blocked and cannot respond in time. The most common type is the input dispatch timeout: if the app has not responded to an input event (a tap or key press) within 5 seconds, the system reports an ANR and can show the "App isn't responding" dialog. Note that it needs a pending input event: a frozen main thread with no touch may produce a different ANR type, or none.
Other ANR types and their default timeouts, from the Android developer docs:
| ANR type | Default timeout |
|---|---|
| Input dispatch timeout | 5 s |
| No focused window (input arrives but no window has focus) | 5 s |
BroadcastReceiver, foreground priority intent (FLAG_RECEIVER_FOREGROUND) | 10 s on Android 13 and lower; 10 to 20 s on Android 14+ |
BroadcastReceiver, background priority intent | 60 s on Android 13 and lower; 60 to 120 s on Android 14+ |
Execute service (onCreate, onStartCommand, onBind) | 20 s foreground service; 200 s background service |
| Content provider not responding | Set by the caller with ContentProviderClient.setDetectNotResponding |
On Android 14 and higher the broadcast timeouts depend on whether the process is CPU-starved. "Foreground priority" refers to the intent flag, not to whether your app is on screen.
Root causes fall into a few buckets: (1) main-thread I/O, such as File.readText(), large SharedPreferences loads, or a synchronous database query; (2) lock contention, where the main thread waits on a synchronized block or lock held by a background thread doing slow work, or a deadlock; (3) heavy CPU work on the main thread, such as parsing a large JSON file or decoding big bitmaps; (4) slow binder calls to system services or other processes. Slow app startup can also cause broadcast receiver and execute service ANRs, because the component cannot run until Application.onCreate finishes.
Detection in debug: enable StrictMode.ThreadPolicy with .detectDiskReads().detectDiskWrites().detectNetwork() and a penalty (penaltyLog(), or penaltyDeath() if you want violations to crash) to catch accidental main-thread I/O.
Detection in production: read ANR clusters in Play Console, Android vitals, Crashes and ANRs, which show the main-thread stack and other threads. On a device, ANR traces are in /data/anr/ (traces.txt on older releases, anr_* files on newer ones); without root, capture them with adb bugreport. From Android 11 (API 30), ActivityManager.getHistoricalProcessExitReasons() returns ApplicationExitInfo records; for REASON_ANR, getTraceInputStream() gives the ANR trace, so you can upload it to your own crash reporting on the next launch.
The usual fix: move the blocking call off the main thread with withContext(Dispatchers.IO) or Dispatchers.Default, keep only the UI update on the main thread, and replace blocking locks the main thread touches with suspending ones (Mutex.withLock) or remove the sharing.
Notes
- The input dispatch ANR timeout is 5 seconds. It fires when the app has not handled a touch or key event within that window.
BroadcastReceivertimeouts depend onFLAG_RECEIVER_FOREGROUND: 10 s (foreground priority) and 60 s (background priority) on Android 13 and lower, extended to 10 to 20 s and 60 to 120 s on Android 14+ when the process is CPU-starved.- Execute service timeouts are 20 s for a foreground service and 200 s for a background service, covering
onCreate,onStartCommandandonBind. onReceiveruns on the main thread. For work longer than a moment, callgoAsync()and finish thePendingResultfrom a background thread, or enqueue aWorkManagerjob. Forgetting to callfinish()aftergoAsync()is itself an ANR cause.- Main causes: main-thread I/O, lock contention or deadlock, heavy CPU work, and slow binder calls. Slow startup can push receivers and services past their timeouts.
- In debug, enable
StrictMode.ThreadPolicy.Builder().detectDiskReads().detectDiskWrites().detectNetwork()with a penalty inApplication.onCreate, inside anif (BuildConfig.DEBUG)check. - ANR traces: Play Console Android vitals (Crashes and ANRs),
/data/anr/on the device (viaadb bugreportwithout root), andApplicationExitInfo.getTraceInputStream()forREASON_ANRrecords from API 30. ApplicationExitInfocomes fromActivityManager.getHistoricalProcessExitReasons(packageName, 0, maxNum). Each record has a reason, a timestamp, the process importance and, for ANRs, the trace.- Use
Dispatchers.IOfor blocking file, network and database calls,Dispatchers.Defaultfor CPU-bound work, and the main dispatcher (the default inlifecycleScope) only for UI updates. - A
synchronizedblock shared between the main thread and a background thread is a hidden ANR cause: the main thread waits while the background thread holds the lock during slow I/O. PreferMutex.withLock, which suspends instead of blocking.
Code example
This shows a classic ANR pattern, a Fragment reading and parsing a large JSON file on the main thread, and the coroutine fix that moves I/O and parsing off the main thread while keeping the UI update on the main thread.
// Before: file read and parse on the main thread can block for seconds
class DataFragment : Fragment(R.layout.fragment_data) {
private val adapter = ItemAdapter() // a ListAdapter<Item, ...>
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
view.findViewById<RecyclerView>(R.id.recycler).adapter = adapter
val raw = File(requireContext().filesDir, "cache.json").readText()
val items = Json.decodeFromString<List<Item>>(raw)
adapter.submitList(items)
}
}
// After: I/O and parsing run off the main thread; only submitList runs on Main
class DataFragmentFixed : Fragment(R.layout.fragment_data) {
private val adapter = ItemAdapter()
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
view.findViewById<RecyclerView>(R.id.recycler).adapter = adapter
val file = File(requireContext().filesDir, "cache.json")
viewLifecycleOwner.lifecycleScope.launch {
val raw = withContext(Dispatchers.IO) { file.readText() }
val items = withContext(Dispatchers.Default) {
Json.decodeFromString<List<Item>>(raw)
}
adapter.submitList(items) // back on the main thread
}
}
}Dispatchers.IOruns the blocking file read;Dispatchers.Defaultruns the CPU-bound parse on a pool sized to the CPU cores.viewLifecycleOwner.lifecycleScopecancels the coroutine when the view is destroyed, so the result is never delivered to a dead view.- In a real app this loading belongs in a repository called from a ViewModel; the dispatcher switch is the part that prevents the ANR.
Run the idea in plain Kotlin
fun main() {
val anrThresholdMs = 5000L
// Simulated main-thread work while an input event is waiting
val mainThreadWorkMs = 7200L
val offloadedWorkMs = 12L
println("=== ANR Simulation ===")
println("Input dispatch ANR threshold: " + anrThresholdMs + " ms")
println("")
println("Before fix: main thread work = " + mainThreadWorkMs + " ms")
println("ANR triggered: " + (mainThreadWorkMs > anrThresholdMs))
println("")
println("After fix: main thread work = " + offloadedWorkMs + " ms")
println("ANR triggered: " + (offloadedWorkMs > anrThresholdMs))
println("")
// Default timeouts (Android 13 and lower for broadcasts)
val timeouts = listOf(
"Input dispatch" to 5000L,
"No focused window" to 5000L,
"BroadcastReceiver (foreground priority)" to 10000L,
"BroadcastReceiver (background priority)" to 60000L,
"Execute service (foreground)" to 20000L,
"Execute service (background)" to 200000L
)
println("ANR timeout types:")
for (entry in timeouts) {
println(" " + entry.first + ": " + entry.second + " ms")
}
println("")
println("Key rule: keep main-thread work short.")
println("Offload I/O to Dispatchers.IO, CPU to Dispatchers.Default.")
}Expected output:
=== ANR Simulation ===
Input dispatch ANR threshold: 5000 ms
Before fix: main thread work = 7200 ms
ANR triggered: true
After fix: main thread work = 12 ms
ANR triggered: false
ANR timeout types:
Input dispatch: 5000 ms
No focused window: 5000 ms
BroadcastReceiver (foreground priority): 10000 ms
BroadcastReceiver (background priority): 60000 ms
Execute service (foreground): 20000 ms
Execute service (background): 200000 ms
Key rule: keep main-thread work short.
Offload I/O to Dispatchers.IO, CPU to Dispatchers.Default.
In production
- Play Console showed an ANR cluster starting with a release that stored a large JSON blob in
SharedPreferences. - The ANR trace showed the main thread waiting for the preferences file to finish loading, inside a
getString()call inApplication.onCreate. - Users on slower devices who tapped during the freeze hit the input dispatch timeout.
- Reproduced it by seeding the same large value and cold-starting a low-end test device while tapping.
- Moved the blob out of
SharedPreferencesinto a file read onDispatchers.IO, and migrated the remaining small settings to DataStore, which reads off the main thread. - Enabled
StrictModedisk-read detection in debug builds so future main-thread disk access shows up during development.
- A
BroadcastReceiverwrote every incoming payload to a database synchronously inonReceive. - On busy devices the write sometimes waited on a database lock held by a sync job, and Play Console ANR clusters showed the main thread stuck inside
onReceive. - Because
onReceiveruns on the main thread, the receiver exceeded the broadcast timeout.
onReceivenow only reads the intent extras and enqueues aOneTimeWorkRequestwithWorkManager; the worker does the database write in the background.- For a receiver that needed a short async step, they used
goAsync()and calledfinish()on thePendingResultin afinallyblock. - ANR clusters for the receiver stopped appearing in the next releases.
Common mistakes
- Reading files or large preferences in onCreate or onViewCreated. This blocks the main thread for the whole read. On slow storage or large files it can take long enough to cause an ANR. Do it on
Dispatchers.IOand post the result back. - Using the Fragment's lifecycleScope instead of viewLifecycleOwner.lifecycleScope for UI work. The Fragment's own scope outlives its view while the Fragment is on the back stack, so a result can arrive after the view is gone.
viewLifecycleOwner.lifecycleScopeis cancelled with the view. - Sharing a synchronized block between the main thread and a background thread. If the background thread holds the lock while doing I/O, the main thread waits and the input timer runs out. Use
Mutex.withLock(which suspends) or keep the whole operation off the main thread. - Doing slow work directly in BroadcastReceiver.onReceive. It runs on the main thread with a timeout. Enqueue
WorkManagerwork, or usegoAsync()and always callfinish(). - Only watching the crash rate. ANRs are reported separately from crashes, in Android vitals under Crashes and ANRs. An app can have a low crash rate and a high ANR rate.
- Running CPU-heavy parsing or decoding on Dispatchers.Main. The main dispatcher is the single UI thread. Heavy work there blocks input handling. Use
Dispatchers.Default.
Interview questions
Answer out loud first. Then reveal the answer and compare it at each depth.
“What causes an ANR in Android and how do you debug one?”
“What are the different ANR timeouts and when do they apply?”
“How do you prevent ANRs in production code?”
“Play Console shows a new ANR cluster. Walk me through your investigation.”
Quiz
What is the default input dispatch ANR timeout in Android?
Which coroutine dispatcher should you use for a blocking file read started from a Fragment?
What does StrictMode.ThreadPolicy with detectDiskReads() do in a debug build?
From Android 11 (API 30), how can an app read the trace of its own previous ANR?
0 of 4 answered
Mini task
15-minute exercise: catch and fix a main-thread ANR
-
Create the ANR. In a test
Fragment, add this toonViewCreated(the sleep stands in for slow storage or parsing):val data = File(requireContext().filesDir, "big.json").readText() Thread.sleep(8_000)Run the app, open the Fragment, and tap the screen a few times while it is frozen. After about 5 seconds you should see the "App isn't responding" dialog.
-
Enable StrictMode. In
Application.onCreate, add:if (BuildConfig.DEBUG) { StrictMode.setThreadPolicy( StrictMode.ThreadPolicy.Builder() .detectDiskReads() .detectDiskWrites() .detectNetwork() .penaltyLog() .build() ) }Run again and filter Logcat by
StrictMode. You should see a disk read violation pointing at thereadText()line. (EnablebuildConfig = trueinbuildFeaturesifBuildConfigis not generated.) -
Fix it. Remove the sleep and replace the synchronous read with a coroutine:
val file = File(requireContext().filesDir, "big.json") viewLifecycleOwner.lifecycleScope.launch { val data = withContext(Dispatchers.IO) { file.readText() } // parse on Dispatchers.Default, then update the UI here } -
Verify. Run the app again. Taps respond immediately and Logcat shows no new
StrictModedisk violations from this Fragment. -
Read a real trace. Put the blocking version back once, trigger the ANR, then run
adb bugreport anr.zipand open theanr_*file underFS/data/anr/in the zip. Find the"main"thread and confirm it is inside youronViewCreated.
Done condition: the fixed Fragment shows no ANR dialog when tapped during loading, Logcat shows no StrictMode disk violations from it, and you have found the main-thread stack in an ANR trace from the bug report.