This blog post introduces one of the important mechanism of Async Task for Android with sample code.
Android implements single thread model and whenever an Android application is launched, a thread is created. Now assume you have long running operations like a network call on a button click in your application. On button click a request would be made to the server and response will be awaited. Now due to the single thread model of Android, till the time response is awaited your UI screen hangs or in other words, it is non-responsive.
We can overcome this by creating a new Thread and implement the run method to perform the time consuming operation, so that the UI remains responsive.
As shown below a new Thread is created in onClick method
public void onClick(View v) {
Thread t = new Thread(){
public void run(){
// Long running operation
}
};
t.start();
}
But since Android follows single thread model and Android UI toolkit is not thread safe, so if there is a need to make some change to the UI based on the result of the operation performed, then this approach may lead some issues.
There are various approaches via which control can be given back to UI thread (Main thread running the application). Handler approach is one among the various approaches.
Handler
Let us look at the code snippet below to understand Handler approach.
public void onClick(View v) {
Thread t = new Thread(){
public void run(){
// Long time comsuming operation
Message myMessage=new Message();
Bundle resBundle = new Bundle();
resBundle.putString("status", "SUCCESS");
myMessage.obj=resBundle;
handler.sendMessage(myMessage);
}
};
t.start();
}
As seen we have modified the original run method and added code to create Message object, which is then passed as parameter to sendMessage method of Handler. Now let us look at the Handler. Note that the code below is present in the main activity code.
private Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
// Code to process the response and update UI.
}
};
After the execution of long running operation, the result is set in Message and passed to sendMessage of handler. Handle will extract the response from Message and will process and accordingly update the UI. Since Handler is part of main activity, UI thread will be responsible for updating the UI.
Handler approach works fine, but with increasing number of long operations, Thread needs to be created, run method needs to be implemented and Handler needs to be created. This can be a bit cumbersome. The Android framework has identified this pattern and has nicely enveloped it into what is called an Android Async Task. Let us look at how it can help simplify things.
Async Task
Android Async Task takes cares of thread management and is the recommended mechanism for performing long running operations.
Let us look at a sample class LongOperation, which extends the AsyncTask below:
private class LongOperation extends AsyncTask<String, Void, String> {
@Override
protected String doInBackground(String... params) {
// perform long running operation operation
return null;
}
/* (non-Javadoc)
* @see android.os.AsyncTask#onPostExecute(java.lang.Object)
*/
@Override
protected void onPostExecute(String result) {
// execution of result of Long time consuming operation
}
/* (non-Javadoc)
* @see android.os.AsyncTask#onPreExecute()
*/
@Override
protected void onPreExecute() {
// Things to be done before execution of long running operation. For example showing ProgessDialog
}
/* (non-Javadoc)
* @see android.os.AsyncTask#onProgressUpdate(Progress[])
*/
@Override
protected void onProgressUpdate(Void... values) {
// Things to be done while execution of long running operation is in progress. For example updating ProgessDialog
}
}
Modify the onClick method as shown below:
public void onClick(View v) {
new LongOperation().execute("");
}
As seen class LongOperation extends AsyncTask and implements 4 methods:
- doInBackground: Code performing long running operation goes in this method. When onClick method is executed on click of button, it calls execute method which accepts parameters and automatically calls doInBackground method with the parameters passed.
- onPostExecute: This method is called after doInBackground method completes processing. Result from doInBackground is passed to this method.
- onPreExecute: This method is called before doInBackground method is called.
- onProgressUpdate: This method is invoked by calling publishProgress anytime from doInBackground call this method.
Overriding onPostExecute, onPreExecute and onProgressUpdate is optional.
Points to remember:
- Instance of Async Task needs to be created in UI thread. As shown in onClick method a new instance of LongOperation is created there. Also execute method with parameters should be called from UI thread.
- Methods onPostExecute, onPreExecute and onProgressUpdate should not be explicitly called.
- Task can be executed only once.
Hope this blog helped you understand Android async task and why it is important in Android application development.
Related posts:
- Android Menus An application menu is critical to any mobile application. This is because real estate in a mobile device is limited, so the developer has to make judicious use of menus...
- Twitter4j OAuth on Android Can your application tweet, can it post on walls of people who like this application? Let’s have a look at how to integrate twitter with an android application. What is...



Thank you a lot Prashant. It is very useful.
Great, worked like a charm!
Prashant, this pattern appears adequate for run-to-completion asynchronous operations. What is the recommended Android pattern for asynchronous operations which periodically or sporadically repeat?
For example, what is the recommended approach for a background job (not wanting to lead an answer by using “task” or “service”) which wakes up, checks query parameters, prepares a web service query, executes the query, marshals query results, posts a notification to observers, and goes to sleep for some short while. When it awakes, it repeats the “job”. It does this over and over until instructed to cancel itself.
This is a Nice Article. Keep up ur good Work !!!!!!!!!!
Hi Lonnie,
As per my understanding for the kind of tasks (Job) that you want to perform, writing a service would be an better approach. Service runs in the background for indefinite period of time and it is possible to control and access the service via the exposed interface.
Thanks a lot .This is very helpful
Hey Prashant,
does “Task can be executed only once” mean it can only be executed once and than again if the task has finished or it can not be executed ever again? =)
Might sound a little weird but I don’t need to call it serveral times over and over again, so it should be executed before I call it again.
Oh, thx for your tutorial by the way, it’s really good =)
Hi very useful BUT..
where you have called new LongOperation().execute(“”) I am calling new CameraTask().execute() and getting an error ‘cannot be resolved to a type’. I have the Async import at the top of the file. I also received an error re ‘private class CameraTask extends AsyncTask’ in that only abstract or final are permitted. I am hoping someone can shed some light on this.
Thanks
hi found misplaced } which fixed it!
Hi, thanks for the good tutorial. How do we get back the result to the calling UI thread.
AsyncTask is either written as anonymous inner classes i.e. within the method or as a private inner class in the same class file. So UI component to be modified can be accessed by declaring the it as global variable.
Example:
private void doSomething() {
new AsyncTask<String, Void, String>(){
@Override
protected void onPostExecute(String result) {
if (result != null && result.trim().length() == 0){
textView.setText(result);
}else{
textView.setText("Empty Input Parameter");
}
}
@Override
protected String doInBackground(String… param){
return param;
}
}.execute("value1");
}
Thanks
Prashant Thakkar
Hi Prashant,
The code the return type of the doInBackground() is String. But i want to load the images from url in background. it is possible…..
Thanks in advanced.
Yeah it possible to fetch image from server.
You can perform any operation in doInBackground() and accordingly return string based on whether operation completed successfully or not. For example
@Override
protected String doInBackground(String… params) {
try{
// fetching image
return success;
}catch(Exception e){
return failed;
}
}
The String returned via doInBackground() is available as input parameter for onPostExecute(String result) method.
Thanks
Prashant Thakkar
The problem with this basic approach is that if something causes the activity instance to be destroyed (like a screen orientation change) while your async task is performing its background processing, then by the time the onPostExecute() method is invoked, back on the UI thread, you will be referencing the old (dead) Activity instance. This leads to the ‘Leaked Window’ error message amongst other things, same goes for onProgressUpdate().
All,
Is it necessary to create a service only to perform a recurring task…?
How about having a Handler…?
I shall invoke sendMessageAtTime(Message, long) instead of dispatchMessage(Message).
In handleMessage(Message), I will call the sendMessageAtTime(Message, long) method, which is nothing but the recurring.
All,
Is it necessary to create a service everytime for a recurring task?
How about using a Handler instead?
I shall call invoke method sendMessageAtTime(Message, long) for the purpose.
Hi,
I am continuosly getting “This task has already been executed. A task can be executed only once.” I want to cancel the current running task and start a new one upon request.
Please suggest,
Json
Hi Prashant,
I am new in android, i read your blog post regularly. Now I am facing one problem, it may not related to AsyncTask, but I hope you help me. I am doing on web base Android Application. I that one view is contain category in table layout. when we click on any category I get the id of that category, pass it in URL, send the request to server, get XML, Parse this XML(XML contain thumb nail image and description), and display that information in table layout exactly belove the selected category. In my case there are many record(more than 50) so it take 1-2 minute to display thumbnail images on table layout. I want to show the dialog box while loading and drawing the thumbnail.
I am trying as u mentioned above. but I am not able to show dialog box at write time and write place. It display the dialog box after displaying all thumbnail(may be the boolean return type of On Click).
Please Give me some solution on it. If u want i will give u my source code also.
Thanks in advance.
thanks. it help me lot
Thabk so much!! Very helpful!!!
I’d like to show ProgressDialog when the data is passing from database to 2nd spinner.
But something wrong in my code. Could you help me, please?
Spinner marke = (Spinner) findViewById(R.id.spinner1); marke.setOnItemSelectedListener(new OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView adapter, View view, int pos, long id) {
new Background().execute(null);//some code
public class Background extends AsyncTask {
@Override
protected void onPreExecute() {
dialog.show();
dialog.setMessage(“Please, wait!”);
}
protected Void doInBackground(Void… params) {
return null;
}
protected void onPostExecute(Void result) {
super.onPostExecute(result);
if (dialog != null) {
dialog.dismiss();
}
}
thanks a lot for this pretty nice article!
hi Prashant,
Thank you for ths nice article. It helped me a lot.
Thanks for this post, it was really helpful.
Saved me a lot.
Thanks a lot for this post.. very well explained!!!
Thank you for a clear explanation of how to use a nested onpostexecute to pass values back to the original activity.
Hai thanx for the post it is really helpful
nice example..its very helpful to me
Thankx prashant for the whole stuff..
I myself solved the problem….
Thanks
Superb Code… and very useful….
This is awesome!!! very understandable post. Thanks for sharing with us. you may check this helpful link…
http://mindstick.com/Articles/c25f0596-db32-4a79-bda4-38535f3b8dc0/?Using%20AsyncTask%20in%20Android%20Application
It is helped me lot to complete my task.
Thanks, this information helps lot
can we restart a background service on the onpostexecute of asynctask? the scenario is : the asynctask is in the inner class named networktask of the service class
greate explanation……..
Thnak u nice explanation
great,
It’s very helpful..Thanx..
Thanx Mr. Prashant for Such a great Explanation. Hope , it will be helpful for me
Thanx Mr. Prashant for Such a great Explanation. Hope , it will be helpful for me
And one question regarding this , how can we Update UI without click on any button . & it will be refresh automatically after five second.
Hi Mr.Prashant
Its really a nice article and neatly framed. Im facing illegal state exception while im doing audio record code where prepare() is being failed. Thereby im suggested to use Async Task . But unable to use it in proper way.
Any inputs regarding this would be appreciated.
Thanks
We are using SQL 2000 -8.00.760 for our Android project.Able connect the database from Labtop(windows 7). But while try the Samecode in PC(windows XP)the error has occured as “No Suitable Driver found”. We have included the sqljdbc4.jar in the Project.
Can you give any solution for the above problem.
In android project(Labtop) able to get the Datas from SQL database and populated in 2 different Spinners. After data entry in the screen, while try to store the data in Database by button click; cause error in the below line
“conn = DriverManager.getConnection(url);”.
Can you give any solution for the above problem.
Dear Vaibhav,
Thanks for writing back.
I would suggest creating an global instance variable for your service at the start of activity, so that you can refer it from onPostExecute method.
hope this helps.
Regards,
Prashant
Dear Kiran,
Thanks for writing back.
Probably you are calling prepare() from some invalid state. Refer following link to check valid states for calling prepare method.
Hope this helps.
Regards,
Prashant
Dear Balasubrmaniam,
Thanks for writing back.
For both the queries that you have raised,I would like to bring to your notice that Android has inbuilt SQLite database, use that.
For more information, I suggest you to refer :
http://www.xoriant.com/blog/mobile-application-development/android-sqlite-database.html
Dear Kiran,
I missed giving the link.
http://developer.android.com/reference/android/media/MediaPlayer.html#prepare()
Regards,
Prashant