Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Androids Handler.post, what happens exactly

since several days, I tried to figure out what exactly happens if I execute code in

void function(){

  //somePreExecutionCode
  new Handler().post(new Runnable(){
    @Override 
    public void run(){
       //someCode
    }
  });
}

It seems like it isn't blocking the UI, so buttons, which calls function() doesn't stuck in the clicked position until someCode has finished. But if somePreExecutionCode starts a progressBar, the progressBar is shown at exactly the same moment, when someCode has finished. I know, there are AsyncTasks for, but is there any other possibility?

And whats the difference between

new Handler().post 

and

View.post

?

like image 710
Ef Ge Avatar asked Apr 10 '14 09:04

Ef Ge


1 Answers

Putting it simply, there are Looper threads, for example, UI thread. Such thread has its own Looper, which runs a message loop for the thread.

Such thread, typically, has a Handler, which processes its Looper's messages - overriding public void handleMessage(Message msg) or executing a Runnable, which was posted to it's looper's message queue.

When you're creating a Handler in the context of UI thread (like you did in your code), it gets associated with UI thread's looper, so your \\someCode runs on UI thread.

I guess, in your use case new Handler().post(Runnable) and View:post(Runnable) are mostly the same, as they both add a Runnable to the UI thread message queue.

But they are not the same.

  • View:post(Runnable) will add a Runnable to the UI thread looper's message queue;
  • Handler:post(Runnable) will add a Runnable to its associated thread looper's message queue

My explanation is pretty much intuitive, so correct me anyone if I am wrong.

like image 151
Drew Avatar answered Oct 27 '22 06:10

Drew