Run some code on the Android main thread.

This is a very simple piece of code to run a Runnable object on the main thread, or UI thread, on Android. The code creates an Handler using the main thread looper. The handler receives a Runnable object to execute on the main thread. It is very handy to update the UI from a background thread or an AsyncTask.


new Handler(Looper.getMainLoooper()).post(new Runnable() {
    @Override
    public void run() {
        // your code here
    }
});

It is also possible to post a Runnable object for execution after some time using postDelayed() and specifying as parameter the delay in milliseconds.


new Handler(Looper.getMainLoooper()).postDelayed(new Runnable() {
    @Override
    public void run() {
        // your code here
    }
}, 1000);

To know more about Handler and Looper you can have a look at my post on this subject.

Unique opportunity! Help a fellow grow his blog!

Hi there! If you’ve read this far maybe you think this was useful, or fun, or I don’t know what but for some reason You Got Here! Great! Please consider sharing this post with your network, I am trying to get The Code Butchery to grow so I can provide more content like this, will you help me in my journey? Thank you!

Share this

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.