Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

runOnUiThread vs Looper.getMainLooper().post in Android

Tags:

android

Can anyone tell me if there's any difference between using runOnUiThread() versus Looper.getMainLooper().post() to execute a task on the UI 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 code something in a class that can't see the Activity (such as an interface).

I'm not looking for a discussion on WHETHER something should be executed on the UI thread, I get that some things can't and a great many things shouldn't, however, some things (like starting up an AsyncTask) MUST be executed from the UI thread.

like image 741
Rich Avatar asked Dec 20 '12 14:12

Rich


People also ask

What is looper getMainLooper ()?

static Looper. getMainLooper() Returns the application's main looper, which lives in the main thread of the application. MessageQueue. getQueue()

What is a looper in Android?

Android Looper is a Java class within the Android user interface that together with the Handler class to process UI events such as button clicks, screen redraws and orientation switches. They may also be used to upload content to an HTTP service, resize images and execute remote requests.

Does handler run on UI thread?

Short answer: they all run on the same thread. If instantiated from an Activity lifecycle callback, they all run on the main UI thread.

What is a handler Android?

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 .


1 Answers

The following behaves the same when called from background threads:

  • using Looper.getMainLooper()

    Runnable task = getTask(); new Handler(Looper.getMainLooper()).post(task); 
  • using Activity#runOnUiThread()

    Runnable task = getTask(); runOnUiThread(task); 

The only difference is when you do that 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 the UI thread and then execute it directly. Posting it as a message will delay the execution until you return from the current UI-thread method.

There is also a third way to execute a Runnable on the UI thread which would be View#post(Runnable) - this one will always post the message even when called from the UI thread. That is useful since that will ensure that the View has been properly constructed and has a layout before the code is executed.

like image 146
zapl Avatar answered Sep 19 '22 17:09

zapl