Looper, Handler & Threading Flashcards
ANDROID › System
- What is a Looper and how does it relate to a thread?
- A Looper runs a message loop for a single thread. Each thread can have at most one Looper (it is thread-local), and the Looper owns that thread's MessageQueue, dispatching messages in order until the loop quits.
- How do you turn an ordinary background thread into one that can process messages?
- Call Looper.prepare() on that thread to create its Looper and MessageQueue, then Looper.loop() to start dispatching. The simpler approach is to use HandlerThread, which does this setup for you.
- What does a Handler do?
- A Handler enqueues Runnables and Messages onto the MessageQueue of the Looper it is bound to, and processes them on that Looper's thread. It is the bridge for posting work to a specific thread and for scheduling delayed work.
- Why is the no-arg Handler() constructor deprecated?
- It implicitly picks up the current thread's Looper, which is error-prone: it can choose the wrong thread or crash if the thread has no Looper. You should pass a Looper explicitly, e.g. Handler(Looper.getMainLooper()).
- How do you run code on the main thread from a background thread using a Handler?
- Create Handler(Looper.getMainLooper()) and call handler.post { ... } (or postDelayed). The Runnable is enqueued on the main thread's MessageQueue and executed by the main Looper.
- What is the difference between Looper.quit() and Looper.quitSafely()?
- quit() stops the loop immediately, discarding all pending messages including non-delayed ones. quitSafely() processes already-due messages then stops, discarding only messages scheduled for the future. The main Looper cannot be quit.
- What is a HandlerThread and why use it?
- HandlerThread is a Thread subclass that prepares a Looper and runs the message loop automatically. You attach a Handler to its Looper to serialize background work onto a single dedicated thread, avoiding manual prepare()/loop() boilerplate.
- What causes an ANR and what are the rough thresholds?
- An ANR happens when the main thread is blocked too long: about 5 seconds for an unhandled input event, ~10 seconds (foreground) for a broadcast, and missed service/job deadlines. Doing I/O, heavy computation, or holding locks on the main thread are common causes.
- How do Message and Runnable differ when scheduling work with a Handler?
- A Runnable carries its own code via post(); a Message carries data (what, arg1, arg2, obj, Bundle) via sendMessage() and is handled in handleMessage(). Internally a posted Runnable is wrapped in a Message, and Messages are pooled via Message.obtain().