Questions
ThreadIntermediate4 min
What is HandlerThread and when to use it?
HandlerThreadHandlerLooper
Answer
What is HandlerThread?
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.
Why Use HandlerThread?
Unlike a regular Thread (which executes once and dies), HandlerThread:
- Stays alive and processes tasks in a queue
- Guarantees sequential execution of tasks
- Provides a Looper that you can attach Handlers to
- Avoids creating new threads repeatedly
Code Example
// 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()
When to Use HandlerThread
| 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 |
HandlerThread vs Other Options
| Approach | Best For |
|---|---|
| HandlerThread | Sequential background tasks needing a Looper |
| ExecutorService | Parallel task execution |
| Coroutines | Modern async programming (recommended) |
| WorkManager | Guaranteed background work |
Important Points
- Always call
quit()orquitSafely()when done quitSafely()processes pending messages before terminating- The Looper is only available after
start()is called
1:1 Mentorship
Get personalized guidance from a Google Developer Expert. Accelerate your career with dedicated support.
Personalized Learning Path
Mock Interviews & Feedback
Resume & Career Guidance
Share & Help Others
Help fellow developers prepare for interviews
Sharing helps the Android community grow 💚