Is there a difference between
new Handler.post(Runnable r);
and
activity.runOnUiThread(Runnable r)
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 .
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).
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.
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.
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