Skip to content

How to Use Android’s HandlerThread in Kotlin

Android, HandlerThread, Kotlin2 min read

Android’s HandlerThread is a powerful tool that can be used to improve the performance and responsiveness of your Android applications. In this article, we’ll explore how to use HandlerThread in Kotlin to run background tasks and communicate with the main thread.

What is HandlerThread?

Before we dive into how to use HandlerThread in Kotlin, let’s first understand what it is. HandlerThread is a class in the Android SDK that extends the Java Thread class and provides a Looper that can be used to process messages and Runnable objects on a dedicated thread. The main advantage of using HandlerThread over a regular Thread is that it simplifies the process of communicating between threads.

Creating a HandlerThread

To create a HandlerThread in Kotlin, you first need to declare a variable of type HandlerThread and initialize it with the constructor. Here’s an example:

1val handlerThread = HandlerThread("MyHandlerThread")

The constructor takes a single parameter, which is the name of the thread. It’s a good idea to give your thread a descriptive name to make debugging easier.

Starting and stopping a HandlerThread

Once you’ve created a HandlerThread, you need to start it using the start() method. This will create a new thread and start the Looper. Here’s an example:


To stop the HandlerThread, you need to call the quit() method. This will stop the Looper and exit the thread. Here’s an example:


Creating a Handler

To communicate with the HandlerThread, you need to create a Handler object. A Handler is an object that can send messages and Runnable objects to a Looper. Here’s an example:

1val handler = Handler(handlerThread.looper)

The constructor takes a single parameter, which is the Looper associated with the HandlerThread. By default, a Handler is associated with the Looper of the thread that creates it, but you can override this by passing a different Looper.

Posting a Runnable to a HandlerThread

To run a task on the HandlerThread, you need to post a Runnable object to the Handler. Here’s an example: : Runnable {
2 override fun run() {
3 // Do some work on the background thread
4 }

The post() method takes a Runnable object and adds it to the message queue of the Handler. The Runnable object’s run() method will be called on the HandlerThread’s thread.

Posting a message to a HandlerThread

In addition to Runnable objects, you can also send messages to a HandlerThread. Messages are objects that contain a bundle of data that can be processed by a Handler. Here’s an example:

1val message = Message.obtain(handler)
2message.what = MY_MESSAGE
3message.obj = "Hello, world!"

The obtain() method creates a new Message object associated with the HandlerThread’s Handler. You can then set properties on the Message object, such as the message type (what) and the message data (obj), before sending it to the Handler using the sendMessage() method.