When may we need to use runOnUiThread in android application?

You have to use runOnUiThread() when you want to update your UI from a Non-UI Thread. For eg- If you want to update your UI from a background Thread. You can also use Handler for the same thing.

From the Docs –

Runs the specified action on the UI thread. If the current thread is
the UI thread, then the action is executed immediately. If the current
thread is not the UI thread, the action is posted to the event queue
of the UI thread.

Syntax –

       Activity_Name.this.runOnUiThread(new Runnable() {

            @Override
            public void run() {
                // your stuff to update the UI

            }
        });

Update –

AsyncTask -

If you want to do some Network operation or anything that blocks
your UI in that case AsyncTask is best options. There are several
other ways for performing the same Background Operations as you can
use Service, IntentService also for doing Background Operations.
Using AsyncTask will help you doing your UI work and also won’t block
your UI until your background Operation is going on.

From the Docs –

AsyncTask enables proper and easy use of the UI thread. This class
allows to perform background operations and publish results on the UI
thread without having to manipulate threads and/or handlers.

Leave a Comment