Search code examples
androidandroid-handler

How to create handler with callbacks that run on a different thread?


I am trying to create a Handler that will handle messages on its own thread

What I am currently doing is running during the onCreate part of the activity this code:

lateinit var _handler: Handler
lateinit var hThread: HandlerThread

fun setUpHandler() {
    hThread = HandlerThread("HandlerThread")
    hThread.start()
    _handler = Handler(hThread.looper, this::callback)
}

the problem is that even though I use a different thread's looper the callback runs on the ui thread.

I tested it by running creating this method:

fun callback(msg: Message): Boolean {
    Log.d("Handler", "got message ${msg.what} in thread main? ${Looper.myLooper() == Looper.getMainLooper()}")
    return true
}

when I call it like this:

_handler.dispatchMessage(Message.obtain(_handler, 1))

I get:

Handler: got message 1 in thread main? true

but when I run it like this:

Handler(hThread.looper).post {
    val msg = Message.obtain()
    msg.what = 2
    callback(msg)
}

I get this message:

Handler: got message 2 in thread main? false

I currently use the second approach, but out of curiosity , is there a way to make the first approach work?

as a side question, is running hThread.quit() in the activity's onDestroy method enough to terminate the extra Thread I started or do I have to do anything else?


Solution

  • As mentioned here the dispatchMessage function runs the Message through the callback on whatever Thread the function is called on... so since your calling it from the UI Thread that's where it appears.

    Also FYI dispatchMessage isn't really used as it defeats the purpose of using a Handler and attaching it to a Thread etc as perfectly demonstrated here.

    quit() terminates the Looper which essentially terminates the infinite while loop in effect that keeps the HandlerThread "alive" in it's run() method, so yes, it should be enough to kill the Thread itself. However, beware that any Message or Runnable currently already executing will not be stopped, and all other Messages or Runnables in the MessageQueue of the Looper will not be executed.