Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android: Why do Handlers post a runnable?

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);
like image 530
Rich Avatar asked Jun 16 '13 11:06

Rich


1 Answers

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.

like image 128
Mr.Me Avatar answered Oct 27 '22 09:10

Mr.Me