AsyncTask In the Simplest And Understandable Language

Nikhil Dhyani
Aug 31, 2018 · 2 min read

When I was learning about it I was so much confused how to use it. Android by default has only one thread known as Main Thread. This is a thread where I/O work is done. For heavy operations like downloading , uploading or doing any database operation we need an alternate solution , for that AysncTask comes for rescue.

AsyncTask

AsyncTask is an abstract class which let the app do long running operation in the background and update the result in the UI (Main) thread.

How to use it?

To use AsynTask we have to make subclass of AsyncTask and specify the data type of param, progress and result.

Note: AsyncTask has 3 parameters “param”, ”progress”,”result”.

AysncTaks<Param,Progress,Result>

If you have any doubt about which type of datatype to specify and where they are going.

This picture makes it damn simple to understand the logic.

https://stackoverflow.com/questions/25647881/android-asynctask-example-and-explanation/25647882#25647882

Note: AsyncTask has 3 parameters “param”, ”progress”,”result”.

Breakdown

onPreExecute()

This method is run before do in background . And this method is used to execute task like setting up progress bar on UI.

doInBackground()

This is the method where we write the code for the long running task.When the execute method is called in the main thread this method is called.

onProgressUpdate()

This method is invoked from doInBackground() . This is used to publish any progress while long running operation is still in process.

onPostExecute()

This method runs after doInBackground() method completes its processing. Result from doInBackground is passed to this method.

PS: To run heavy operation like downloading , uploading or doing any database operation you need async task. And to run the task in background thread you need to call it using .execute.

Ex: AsyncTaskLearner.execute()

Few Things To Keep In Mind

  1. The task instance must be created on the UI thread.
  2. onPreExecute(), doInBackground(Params…), onProgressUpdate() and onPostExecute() should not be called manually.

https://stackoverflow.com/questions/25647881/android-asynctask-example-and-explanation/25647882#25647882

The above given link is the stack overflow answer link which is simply superb. And it will help you to clear doubt.

Nikhil Dhyani

Written by

I write about topics which I learn. Interested in android and hacking.

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade