Android looper

Examples of using Android looper

Class used to run a message loop for a thread. Threads by default do not have a message loop associated with them;

Looper

Creating a looper

 var handler: Handler? = null
Thread {
    log("${Thread.currentThread()} started")
    log("Before call Looper.prepare() ${Thread.currentThread()} looper ${Looper.myLooper()}")
    Looper.prepare()
    log("After call Looper.prepare() ${Thread.currentThread()} looper ${Looper.myLooper()}")

    handler = object : Handler(Looper.myLooper()!!) {

        override fun handleMessage(msg: Message) {
            log("msg.arg1: ${msg.arg1}")
            if (msg.arg1 == -1) {
                looper.quit()
            }
        }
    }
    Looper.loop()
    log("${Thread.currentThread()} finished")
}.start()


while (handler == null) {
    Thread.sleep(100)
}

handler!!.apply {
    arrayOf(1, 2, -1, 3).forEach {
        sendMessage(Message.obtain().apply { arg1 = it })
    }
}