Android – What is AsyncTask?

By -

Hi,

Here i am going to discuss about AsyncTask to be used in Android. Do you know about AsyncTask and used for what?

Well,

  1. AsyncTask enables proper and easy use of the UI thread.
  2. AsyncTask is used when you want to perform long awaited task in background.
  3. AsyncTask publish result on the UI thread(display result to the UI) without having to manipulate any threads or handlers. It means that user doesn’t bother about Thread management, everything is managed by itself. And thats why it is known as Painless Threading, see below point.
  4. It is also known as Painless Threading.
  5. The result of AsyncTask operation is published on UI thread.
  6. It has basically 4 methods to override: onPreExecute, doInBackground, onProgressUpdate and onPostExecute.
  7. Once AsyncTask is created(same as below example), we can execute it by using execute method. 
    new LongOperation().execute(params);
    
For example:
private class LongOperation extends AsyncTask {

@Override
protected void onPreExecute() {
// Things to be done before execution of long running operation. For example showing ProgessDialog
}

@Override
protected String doInBackground(String... params) {
// perform long running operation operation
return null;
}

@Override
protected void onPostExecute(String result) {
// execution of result of Long time consuming operation
}

@Override
protected void onProgressUpdate(Void... values) {
// Things to be done while execution of long running operation is in progress. For example updating ProgessDialog
}
}

Note:
Many times you are required forcefully cancel the running AsyncTask, so to know more about this, please have a look at my article: Cancel AsyncTask in Android

 
 
 
 

Paresh Mayani

Paresh Mayani is a lead android developer from India. Currently, He is Sr. Software engineer at InfoStretch Solutions Pvt. Ltd. He has been developing android apps since very 1st version i.e. Android 1.5, he says he has seen days and nights of Android history. He is the Head/Organizer of Google Developers Group (GDG), Ahmedabad