Day 6 : Delegating some work to other thread.

1 min read


Dear Friends

Today we gonna start a very important concept in android applications (as if others were not important).  A good android programmer keeps his UI Thread free to perform animations , updating UI elements fast so application doesn’t look sluggish.

So what is UI Thread ?

UI thread or main thread is the thread that is responsible for updating UI elements , performing animations, interacting with other activities and components of android.  As its name suggests its the thread which is used by Android app whenever something needs to be done in UI of application.

An application by default  has a  UI Thread.  Now if we want to spawn a new thread we use another Android Class called Asynctask.

Please have a look at below code snippet

public class RegisterUserTask extends AsyncTask<Void, Integer, Boolean> {
protected Boolean doInBackground(Void... params) {


To create Asynctask  , java class has to be extended from AsyncTask.  Now you need to override a method doInBackground() and now you can do your task in this method.  Android OS when tries to executes whaever in the doInBackground in a new thread (worker Thread) other than UI Thread. Thus whatsoever operation is done in doInBackground is performed on alternative thread , thus keeping our UI Thread free for reponding to user touches, activity transitions etc.

Moresoover its a good programming practice to spawn a new thread and do long running operation in that thread so that UI Thread is free to do cooler things on UI.


How do UI Thread and Asynctask communicate ?

Android has a very nice object called Handler that helps us when Worker Thread wants to communicate with UI Thread. Why ?

Suppose your worker thread has done its operation and now it has some results . So you want to show result to user and for that you need to update UI Elements.

As per Android only UI Thread can touch UI Elements. if anytime worker thread tries to access UI Elements an exception is thrown , since this is an invitation to lots of problems. Thats how good OS android saves crucial time of developer.

But now the problem is how worker thread gonna update UI. For this a Handler object is created

public Handler handler = new Handler(){
    public void handleMessage(Message msg) {

so whatever message is passed to the Handler , it can receive message in handleMessage method.  So whatever code is executed in handleMessage is executed on UI Thread.  So our UI Elements can be updated in handleMessage().

In worker thread doInBackground method , you will write code as

Message msg = new Message();





Homework :

Create a worker thread using Asynctask , perform string reversal inside it and show results in UI.


Happy Coding !