Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between Handler.post(Runnable r) and Activity.runOnUiThread(Runnable r) [duplicate]

Is there a difference between

new Handler.post(Runnable r); 

and

activity.runOnUiThread(Runnable r) 
like image 650
VinceFR Avatar asked Sep 17 '11 06:09

VinceFR


People also ask

What is Handler and runnable?

A Handler allows you to send and process Message and Runnable objects associated with a thread's MessageQueue . Each Handler instance is associated with a single thread and that thread's message queue. When you create a new Handler it is bound to a Looper .

What is the difference between thread and handler thread in Android?

Threads are generic processing tasks that can do most things, but one thing they cannot do is update the UI. Handlers on the other hand are background threads that allow you to communicate with the UI thread (update the UI).

What is Post runnable in Android?

post :post causes the Runnable to be added to the message queue, Runnable : Represents a command that can be executed. Often used to run code in a different Thread. run () : Starts executing the active part of the class' code.


1 Answers

From the official Handler docs

Handler

There are two main uses for a Handler:

(1) To schedule messages and runnables to be executed as some point in the future.

(2) To enqueue an action to be performed on a different thread than your own.

In short, Handler is used to manage different Runnables.

runOnUiThread

It is used to execute the non-UI operation on the UI Thread, example if you want to update the screen from AsyncTask's doInBackground() you have to write the part of code that update's the UI inside the runOnUiThread(). But again that will block the UI.

like image 90
Lalit Poptani Avatar answered Oct 05 '22 15:10

Lalit Poptani