What\'s the differences/ advantages / drawbacks between using Activity.runOnUiThread
or Handler.post(runnable action)
in android ?
see here. if in UiThread
, runOnUiThread()
is called immediately, post()
will be called after all the message handled. if not in other thread, runOnUiThread()
is the same as post()
.
public final void runOnUiThread(Runnable action) {
if (Thread.currentThread() != mUiThread) {
mHandler.post(action);
} else {
action.run();
}
}
Activity.runOnUiThread()
is a special case of more generic Handlers. With Handler
you can create your own event query within your own thread. Using Handlers instantiated with default constructor doesn't mean "code will run on UI thread" in general. By default, handlers binded to Thread from which they was instantiated from.
To create Handler that is guaranteed to bind to UI (main) thread you should create Handlerobject binded to Main Looper like this:
Handler mHandler = new Handler(Looper.getMainLooper());
Moreover, if you check the implementation of runOnuiThread()
method, it is using Handler to do the things:
public final void runOnUiThread(Runnable action) {
if (Thread.currentThread() != mUiThread) {
mHandler.post(action);
} else {
action.run();
}
}
As you can see from code snippet above, Runnable action will be executed immediately, if runOnUiThread()
is called from the UI thread. Otherwise, it will post it to the Handler, which will be executed at some point later.
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.