BeCuriouzLearn something new every day
Why Android Shows "App Isn't Responding" Even When Your Code Is Technically Fine
💡 An ANR isn't caused by slow code as such but by a blocked main thread, whether it's busy itself or just waiting on something else.
Every Android app has one main thread (also called the UI thread). It handles touches, draws frames, and runs lifecycle callbacks one message at a time. If that thread gets stuck, the system notices, and after a set time it shows the dreaded ANR ("Application Not Responding") dialog, which lets the user close your app.
The official triggers are specific. An ANR fires if your app hasn't responded to an input event (a tap or key press) within 5 seconds. It also fires if a BroadcastReceiver doesn't finish onReceive in time (10 seconds when the app has something in the foreground), if a service started with startForegroundService doesn't call startForeground within 5 seconds, or if a service's onCreate/onStartCommand or a JobService callback runs longer than a few seconds. The input timer is tied to an input event the app hasn't handled yet. A frozen app that nobody touches may not trigger the input ANR, but the first tap starts the countdown.
The obvious causes are disk or network I/O on the main thread (a big SharedPreferences read, a database query) and long calculations. The sneaky causes are cases where the main thread does almost nothing itself but waits: a synchronous Binder call to another process that's slow to answer, or a synchronized block whose lock is held by a background thread doing slow work. In both cases your heavy work sits "off the main thread", yet the UI thread is still blocked.
The fix is to keep the main thread free to handle the next message. Move I/O to withContext(Dispatchers.IO), avoid locks shared between the UI and slow background work (Android suggests coroutine Mutex.withLock instead), and turn on StrictMode during development so accidental main-thread disk and network access gets flagged before it ships.