The following behaves the same when called from background threads
via Looper.getMainLooper()
Runnable task = getTask(); new Handler(Looper.getMainLooper()).post(task);
via Activity#runOnUiThread()
Runnable task = getTask(); runOnUiThread(task);
The only difference is when you do this from the UI thread, since
public final void runOnUiThread(Runnable action) { if (Thread.currentThread() != mUiThread) { mHandler.post(action); } else { action.run(); } }
will check if the current thread is already a UI thread, and then execute it directly. Posting as a message delays execution until you return from the current user interface method.
There is also a third way to execute Runnable in the user interface thread, which will be View#post(Runnable) - this message will always be published even when called from the user interface thread. This is useful because it ensures that the View been properly designed and has a layout before executing the code.
zapl Dec 20 '12 at 15:00 2012-12-20 15:00
source share