A Handler
is an object maintaining a message queue for the asynchronous processing of messages or Runnable
objects. You can use a Handler
for asynchronous processes as follows:
var handlerThread : HandlerThread? = null // or: lateinit var handlerThread : HandlerThread ... fun doSomething() { handlerThread = handlerThread ?: HandlerThread("MyHandlerThread").apply { start() } val handler = Handler(handlerThread?.looper) handler.post { // do s.th. in background } }
If you create one HandlerThread
as in this code snippet, everything that is posted gets run in the background, but it is executed sequentially there. This means handler.post{}
will run the posts in series. You can, however, create more HandlerThread
objects to handle the posts in parallel. For true parallelism, you’d have to use one HandlerThread
for each execution.
Note Handler
was introduced in Android a long time before the new java.util.concurrent
package was available in Java 7. Nowadays for your own code, you might decide to favor the generic Java classes over Handler
without missing anything. Handler
, however, quite often show up in Android’s libraries.