Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When may we need to use runOnUiThread in android application?

I have a code sample that uses this function to run a thread runOnUiThread. why and when may we need to use it?

edit

What about to use AsyncTask class, what's the pros and cons??

like image 247
Adham Avatar asked Apr 13 '12 04:04

Adham


People also ask

How do I use runOnUiThread on Android?

Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project. Step 2 − Add the following code to res/layout/activity_main. xml. In the above code, we have taken one button and text view, when you click on button , it will update text view.

How does runOnUiThread work?

Also, runOnUiThread is an method of Activity class, it 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.

What is run on UI thread Android?

User Interface Thread or UI-Thread in Android is a Thread element responsible for updating the layout elements of the application implicitly or explicitly. This means, to update an element or change its attributes in the application layout ie the front-end of the application, one can make use of the UI-Thread.


2 Answers

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.

like image 152
Lalit Poptani Avatar answered Oct 09 '22 00:10

Lalit Poptani


To update userinterface from thread you need to use runOnUiThread. But using asynctask is better than using runonuithread. android-runonuithread-vs-asynctask this link can help you

like image 34
Hardi Shah Avatar answered Oct 09 '22 00:10

Hardi Shah