HandlerThread is a Thread subclass that has its own Looper built-in, making it easy to handle messages and runnables sequentially on a background thread.
Unlike a regular Thread (which executes once and dies), HandlerThread:
// Create and start HandlerThread
val handlerThread = HandlerThread("MyBackgroundThread")
handlerThread.start()
// Create Handler attached to HandlerThread's Looper
val backgroundHandler = Handler(handlerThread.looper)
// Post tasks to run on background thread
backgroundHandler.post {
// This runs on HandlerThread, not UI thread
val data = fetchDataFromNetwork()
// Switch to UI thread to update UI
mainHandler.post {
updateUI(data)
}
}
// Don't forget to quit when done
handlerThread.quitSafely()
| Use Case | Why HandlerThread |
|---|---|
| Serial background tasks | Tasks execute one after another |
| Camera callbacks | Needs dedicated thread with looper |
| Sensor data processing | Continuous stream of events |
| File I/O operations | Sequential reads/writes |
| Database operations (pre-Room) | Ordered transactions |
| Approach | Best For |
|---|---|
| HandlerThread | Sequential background tasks needing a Looper |
| ExecutorService | Parallel task execution |
| Coroutines | Modern async programming (recommended) |
| WorkManager | Guaranteed background work |
quit() or quitSafely() when donequitSafely() processes pending messages before terminatingstart() is calledMark this when you can explain the answer in your own words.
Help fellow developers prepare for interviews
Sharing helps the Android community grow ๐