🚀 Enrollments Open for Jetpack Compose Cohort 3 — 4 Weeks of Live Learning to Build Modern Android UIs 💚Join Now
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 CaseWhy HandlerThread
Serial background tasksTasks execute one after another
Camera callbacksNeeds dedicated thread with looper
Sensor data processingContinuous stream of events
File I/O operationsSequential reads/writes
Database operations (pre-Room)Ordered transactions

HandlerThread vs Other Options

ApproachBest For
HandlerThreadSequential background tasks needing a Looper
ExecutorServiceParallel task execution
CoroutinesModern async programming (recommended)
WorkManagerGuaranteed background work

Important Points

  • Always call quit() or quitSafely() when done
  • quitSafely() processes pending messages before terminating
  • The Looper is only available after start() is called

Want to master these concepts?

Join our live cohorts and build production-ready Android apps.

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

Limited slots available each month