Android: Application Not Responding (ANR)
Educational use only. Content explains errors and defensive fixes for systems you own or are authorised to test. Do not use any technique here to access data, accounts, or networks without permission.
Root Cause
An ANR dialogue appears when an Android application's UI thread (the main thread) is blocked for too long (typically 5 seconds for input events or broadcast receivers). The UI thread is responsible for handling user interactions and rendering the screen. If you perform heavy operations—like complex database queries, network requests, large image processing, or infinite loops—directly on the UI thread, the application freezes, becomes unresponsive to user taps, and the OS prompts the user to kill it.
Fix / Solution
Never perform blocking I/O or heavy computation on the main thread. Offload these tasks to background threads. In modern Android development with Kotlin, the standard and most efficient way to handle this is using Kotlin Coroutines with `Dispatchers.IO` or `Dispatchers.Default`. Once the background work is complete, use `withContext(Dispatchers.Main)` to switch back to the UI thread to update the views.
Code Snippet
// ❌ Blocking the UI thread causes an ANR
fun onLoginClick() {
val result = networkApi.loginSync(user, pass); // Network call blocks main thread
textView.text = result;
}
// ✅ Using Kotlin Coroutines to offload work
fun onLoginClick() {
lifecycleScope.launch {
// Switch to background thread for network call
val result = withContext(Dispatchers.IO) {
networkApi.loginSync(user, pass)
}
// Automatically resumes on UI thread to update view
textView.text = result;
}
}