First of all, there is only ONE UI Thread, and it is the main thread that runs the application, looking at this answer will help you understand Threads in android much better:
The UIThread is the main thread of execution for your application.
This is where most of your application code is run. All of your
application components (Activities, Services, ContentProviders,
BroadcastReceivers) are created in this thread, and any system calls
to those components are performed in this thread.
Now, you want to perform actions that require access to the UI Thread(e.g. displaying something on the screen, animating a view, ...etc), So, you have more than an option to achieve that:
1- use the method runOnUIThread()
:
This method uses the current Activity context or the application context in order to run the wrapped-in-it code inside the UI thread(main thread), only you have to use its signature anywhere in the running activity:
runOnUiThread(new Runnable() {
@Override
public void run() {
mInfo.setText(str);
}
});
or even you can run it from outside the current activity by holding the activity or the application context anywhere and hence you will be able to run it even from a normal class:
MainActivity.mContext.runOnUiThread(new Runnable() {
@Override
public void run() {
mInfo.setText(str);
}
});
2- use AsyncTask
:
AsyncTask is the android way to do a background work in a background thread then apply the result to the main thread(UI Thread).
All you have to do is use the method doInBackground()
provided by AsyncTask
in order to handle background work that has to be done in a worker thread(like handling HTTP requests in your case), and then use the method postExecute()
in order to reflect the result to the UI Thread:
private class LongOperation extends AsyncTask<String, Void, String> {
@Override
protected String doInBackground(String... params) {
// handle your worker thread work here
return "result";
}
@Override
protected void onPostExecute(String result) {
// update your UI here
}
}
have a look here to put your hands better on it.