Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the difference between Activity.runOnUiThread(runnable action) and Handler.post()?

Tags:

android

What's the differences/ advantages / drawbacks between using Activity.runOnUiThread or Handler.post(runnable action) in android ?

like image 665
matskn Avatar asked Dec 03 '09 12:12

matskn


People also ask

What is Handler post?

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 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

Activity.runOnUiThread, like it's name implies, will execute the Runnable in the thread that is currently responsible for the UI. So, if you have a CPU intensive task, it can make the UI unresponsive for a short period of time. Conversely, Handler provides a way for you to create a thread, run some code, and notify the UI when you are done (i.e Handler.sendMessage).

The docs for Handler state this better than I can:

When a process is created for your application, its main thread is dedicated to running a message queue that takes care of managing the top-level application objects (activities, broadcast receivers, etc) and any windows they create. You can create your own threads, and communicate back with the main application thread through a Handler. This is done by calling the same post or sendMessage methods as before, but from your new thread. The given Runnable or Message will than be scheduled in the Handler's message queue and processed when appropriate.

like image 167
Erich Douglass Avatar answered Sep 29 '22 05:09

Erich Douglass