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> {

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

		protected Void doInBackground(String... params) {
			// perform long running operation operation
			return null;
		protected void onPostExecute(Void result) {
			// execution of result of Long time consuming operation
		protected void onProgressUpdate(Void... values) {
		// Things to be done while execution of long running operation is in progress. For example updating ProgessDialog

Some time you are required forcefully cancel the ongoing AsyncTask, read article on: Cancelling AsyncTask in Android.

Paresh Mayani

Lazy android developer, exploring the horizon of android development since 7 years, currently working as a Technical Lead - Android at Simform Solutions, India. Former Application Architect at KarConnect. He is the Head/Organizer of Google Developers Group (GDG), Ahmedabad

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