Recent Posts

Site Creator

Asynctask : Delegate tasks and keep UI thread free

Posted on

Dear reader

In life there are two ways to achieve our objective either we work hard and we reap the benefits or someone else works and we reap the benefits.

 

for eg our bike is not functioning properly so rather that fixing the bike ourselves we try to take help from bike service engineer.
Similarly if we are not well , so rather than taking medicines ourselves we would like to get a prescription from a doctor.

 

In addition to this if we are busy with work we sometimes delegate few tasks to different other helpers so that task can be completed.

 

So putting above analogy in Android programming paradigm, we actually want to delegate our task to a different piece of program which can do the task more efficiently.

 

In an Android program we spawn a thread for two reasons (In fact there can be many more..)

 

1. We want to keep our UI thread free so that it can respond to touch events very well. Further Keeping our UI Thread free for touch event saves our program from dreaded Android Not Responding dialog.
2. We want to delegate a task to a thread so that it can run in background and our UI thread is free to perform stunning animation work.

 

Since android is based on java language so technically a thread ( extended from a Thread class or implemented using a runnable) can be used for background task. So now whenever task is completed there should be some way so that response notification / data from a thread can be transferred back to UI Elements in UI Thread. Also there is a strict requirement that Android UI Elements can only be accessed via UI Thread. So for eg whenever it comes to update UI elements after work is completed by background thread , there has to be some way so that communication between UI thread and background thread can be made. So now its a kind of mess.

 

To reduce this complexity of coding android has its own way of spawning background thread and saved developer from the critical mess of threads. Lets have a look at below code snippet

 

Custom thread class extends Asynctask. Then this class overrides doInBackground() method. So whatever is there in doInBackground it automatically performed on a background thread. For eg downloading a large file from internet is done in background thread.

Effect

Now UI thread is free to respond to touch events , perform animations, open activities , pick call, respond to notifications etc.

Hope this helps.

Happy coding!







Disclaimer: The aforesaid writeup by Relsell Global writer is for the general understanding of the readers. It does not render any professional advice or opinion.

SHARE THIS PAGE!