RunOnUiThread vs Looper.getMainLooper (). message in android

Can someone tell me if there is a difference between using runOnUiThread () and Looper.getMainLooper (). post () to execute a task in a user interface thread in Android?

The only thing I can determine is that since runOnUiThread is a non-static activity method, Looper.getMainLooper (). post () is more convenient when you need to encode something in a class that cannot see an action (for example, an interface).

I am not looking for a discussion that something should be executed in the user interface thread, I understand that some things cannot and many things should not, however some things (for example, starting AsyncTask) MUST be executed from the user interface thread.

Thank,
R.

+71
android android-ui
Dec 20 '12 at 14:46
source share
1 answer

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.

+144
Dec 20 '12 at 15:00
source share
β€” -



All Articles