Difference between android runOnUiThread and simple code in java

Mohit Gaur picture Mohit Gaur · Jan 13, 2017 · Viewed 12.1k times · Source

I am a beginner in android application development.I am working with threads in android.I have read about a runOnUiThread which run code on main UI(if i am not wrong?i guess.).

My question is what is the difference between normal code on main UI and code inside runOnIUThread.

Example:1

class A
{
getDataFromServer(foo);//Code on mainUI
}

Example:2

getActivity.runOnUiThread(new Runnable(){
@Override
public void run(){
getDataFromServer(foo);
}
});

What is difference in both example.Please help me.Your response will be a new learning for me.

Answer

Charuක picture Charuක · Jan 13, 2017

Assuming that you meant simple code for UIThread code,

What is a thread ?

A thread defines a process running

First runOnUiThread ..

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 UIThread

  • Main thread of execution for your application
  • Most of your application code will run here onCreate, onPause, onDestroy, onClick, etc.

    So simply Anything that causes the UI to be updated or changed HAS to happen on the UI thread

When you explicitly spawn a new thread to do work in the background, this code is not run on the UIThread.Now what if you want to do something that changes the UI? Then you are welcome to runOnUiThread

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.