Looper, Handler & Threading Interview Questions
ANDROID › System
What are Looper, Handler and MessageQueue, and how do they work together?
What a strong answer covers: A Looper runs a loop on a thread, taking messages from that thread's MessageQueue one at a time and dispatching them. A Handler is bound to a Looper: it posts messages or Runnables to its queue, optionally delayed, and they run on the Looper's thread. The main thread has a Looper that processes input, lifecycle callbacks and drawing, which is why work on it must be short.
Why can only the main thread touch views, and what happens if you update a view from a background thread?
What a strong answer covers: The view system isn't thread-safe, so Android enforces a single UI thread. Updating a view from another thread throws CalledFromWrongThreadException in most cases (checked in ViewRootImpl). Switch back with withContext(Dispatchers.Main), View.post, runOnUiThread, or a Handler on the main Looper.
What is an ANR, and what usually causes one?
What a strong answer covers: Application Not Responding: the system shows a dialog when the main thread is blocked for about 5 seconds on input, when a BroadcastReceiver takes too long (around 10 seconds in the foreground), or when a service doesn't start in time. Common causes: disk or network I/O on the main thread, lock contention with a background thread, slow SharedPreferences commits, heavy work in onCreate, and Binder calls to a slow system service.
How can a Handler leak an Activity, and how do you avoid it?
What a strong answer covers: A non-static inner Handler or a posted Runnable holds an implicit reference to the activity. If a message is delayed (postDelayed for a minute), the queue holds the message, the message holds the handler, and the handler holds the activity, so it can't be collected after destruction. Fixes: remove callbacks in onDestroy (removeCallbacksAndMessages(null)), use lifecycle-aware coroutines instead, or a static handler with a weak reference.
How do coroutines on Dispatchers.Main relate to the Looper, and what does it mean that the main thread is also used for frame rendering?
What a strong answer covers: Dispatchers.Main posts resumed coroutines as messages to the main Looper, so they share the queue with input events, lifecycle callbacks and Choreographer frame callbacks. A frame at 60 Hz has about 16 ms; if your coroutine work between suspension points exceeds that, frames drop. Long work must move to another dispatcher, and big loops on Main should yield. A strong answer mentions Choreographer and RenderThread.