Android basics: running code in the UI thread Android basics: running code in the UI thread android android

Android basics: running code in the UI thread


None of those are precisely the same, though they will all have the same net effect.

The difference between the first and the second is that if you happen to be on the main application thread when executing the code, the first one (runOnUiThread()) will execute the Runnable immediately. The second one (post()) always puts the Runnable at the end of the event queue, even if you are already on the main application thread.

The third one, assuming you create and execute an instance of BackgroundTask, will waste a lot of time grabbing a thread out of the thread pool, to execute a default no-op doInBackground(), before eventually doing what amounts to a post(). This is by far the least efficient of the three. Use AsyncTask if you actually have work to do in a background thread, not just for the use of onPostExecute().


I like the one from HPP comment, it can be used anywhere without any parameter:

new Handler(Looper.getMainLooper()).post(new Runnable() {    @Override    public void run() {        Log.d("UI thread", "I am the UI thread");    }});


There is a fourth way using Handler

new Handler().post(new Runnable() {    @Override    public void run() {        // Code here will run in UI thread    }});