Can someone explain why Handlers post a runnable? Does overriding handleMessage and sending a message do the same thing?
I've written some untested code to show how I think these two ways would be implemented. Please correct me if I'm wrong in my approach.
Handler with Post:
handler.post(new Runnable() {
@Override
public void run() {
imageView.doSomething();
}
});
Handler with handleMessage:
final Handler handler = new Handler() {
@Override
public void handleMessage(Message message) {
imageView.doSomething();
}
};
handler.sendMessage(message);
Both code snippets work the same, conventionally you use Handler.postRunnable when you want to execute some code on the UI Thread without having to know anything about your Handler object. It makes sense in many cases where arbitrary code needs to be executed on the UI Thread.
But in some cases you want to organise what is being sent to the UI Thread and have specific functions you want to execute that way you can use sendMessage.
I don't think there is a performance penalty for using either one above the other. It is up to you, to use whatever you think suits you more.
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