Explain the concept of Looper, Handler, and HandlerThread in Android.

Instruction: Provide a detailed explanation of the relationship and use-cases of Looper, Handler, and HandlerThread in Android. Include examples where appropriate.

Context: This question assesses the candidate's understanding of Android's message passing mechanisms. It probes into the candidate's ability to explain complex background processing, threading models, and how they manage communication between the main thread and background threads in Android applications.

Updated

Official answer

A Looper dispatches queued messages on one thread. A Handler is associated with a particular Looper and posts Runnables or Messages to that thread's queue. Posting from a worker to a Handler for the main Looper schedules main-thread execution; the posting thread does not run the callback itself.

HandlerThread is a Thread with a prepared Looper. Start it before obtaining its Looper, then create a Handler explicitly bound to that Looper. Its callbacks run serially. A long callback blocks later messages on that same thread, so a HandlerThread is not parallel execution and does not make arbitrary work fast.

For an API that requires a Handler, a dedicated HandlerThread can receive device callbacks. After processing a result, a main-thread Handler can publish a small UI update only if the current view still owns that request. Cancel/remove obsolete callbacks and release references when the owner ends. quitSafely processes already-due messages and drops future delayed messages; it does not interrupt a callback currently running.

For ordinary asynchronous I/O, consider structured coroutines or an Executor instead. A background thread does not need a Looper unless it uses a message-loop API. Neither a HandlerThread nor a coroutine keeps work durable across process death; use a persistent-work mechanism when required. Test cancellation, a stale UI result and orderly shutdown.

HandlerThread API

Related Questions