Android – What is AsyncTask?

By -

I am going to discuss about AsyncTask. Do you know about AsyncTask and what are the usage of it?

Here are some of the points:

  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<String,Void,Void> {

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

		@Override
		protected Void doInBackground(String... params) {
			// perform long running operation operation
			return null;
		}
		
		@Override
		protected void onPostExecute(Void result) {
			super.onPostExecute(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:
Some time you are required forcefully cancel the ongoing AsyncTask, read article on: Cancelling AsyncTask in Android.

CEO & Co-Founder at SolGuruz® | Organiser @ GDG Ahmedabad | Top 0.1% over StackOverflow | 15+ years experienced Tech Consultant | Helping startups with Custom Software Development

Loading Facebook Comments ...
Loading Disqus Comments ...