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
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.
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.
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().
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.
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()
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With