14

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);
Rich
  • 785
  • 1
  • 9
  • 22

1 Answers1

12

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.

edwoollard
  • 12,245
  • 6
  • 43
  • 74
Mr.Me
  • 9,192
  • 5
  • 39
  • 51
  • Well, there's a very very small performance hit for creating a new object (the runnable). But it's negligible. – eordano Feb 07 '14 at 02:54
  • 2
    However, if you want to execute the code on the UI Thread, you have to create the Handler in the UI Thread, or use "new Handler(Looper.getMainLooper())". With "new Handler()" you create a Handler in the current thread, that does not have to be the main thread. – Kuno May 23 '14 at 13:29
  • 通常情况下,当你想在UI线程上执行一些轻量级的代码,比如更新UI的某些部分,或者执行一些简单的计算,使用`postRunnable`更为适合。这是因为`postRunnable`不需要创建`Message`对象,而是直接将`Runnable`对象添加到UI线程的消息队列中,从而减少了一些开销。这样编码也更加直接,更加简单。 – linjiejun May 12 '23 at 02:54
  • good answer .Thk u – linjiejun May 12 '23 at 02:55