Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use Handler and handleMessage in Kotlin?

Java code:

private final Handler mHandler = new Handler() {
    @Override
    public void handleMessage(Message msg) {
       // code here
    }
};

How to convert this java code to Kotlin?

I tried this:

private val mHandler = object : Handler() {
    fun handleMessage(msg: Message) {
       // code here
    }
}

But this is seems to be incorrect and gives a compile time error on object

like image 645
nb2998 Avatar asked Aug 26 '18 10:08

nb2998


People also ask

What is Handler in Kotlin?

What is the use of handler class in Android? There are two main uses for a Handler: (1) to schedule messages and runnables to be executed at some point in the future; and (2) to enqueue an action to be performed on a different thread than your own.

What can I use instead of handler in Kotlin?

Thanks to the Kotlin Coroutines and Jobs mechanism, we can get away from using Handlers in this scenario, by creating lightweight Coroutine Jobs and cancelling them in between to just stop the desired task from getting executed.

How do you use a handler?

There are two methods are in handler. Post() − it going to post message from background thread to main thread using looper. sendmessage() − if you want to organize what you have sent to ui (message from background thread) or ui functions. you should use sendMessage().

Does handler run on UI thread?

Android handles all the UI operations and input events from one single thread which is known as called the Main or UI thread. Android collects all events in this thread in a queue and processes this queue with an instance of the Looper class.


1 Answers

You may do it a bit easier (without WeakReference) by passing looper to handler:

val handler = object:  Handler(Looper.getMainLooper()) {
        override fun handleMessage(msg: Message) {
            doStuff()
        }
    }
like image 134
Pietrek Avatar answered Oct 06 '22 00:10

Pietrek