Understanding Android AsyncTask

AsyncTask is a mechanism for executing operations in a background thread without having to manually handle thread creation or execution.It is designed to be used for short operations (a few seconds at the most). If you need to keep threads running for long periods of time, it is highly recommended you use the various APIs provided by the java.util.concurrent package such as Executor, ThreadPoolExecutor and Service.

Creating MyAsyncTask :

private class MyAsyncTask< Params, Progress, Result> {……}

The three types used by an asynchronous task are the following:

  1. Params, the type of the parameters sent to the task upon execution.
  2. Progress, the type of the progress units published during the background computation.
  3. Result, the type of the result of the background computation.

4 Stages of AsyncTask :

  • PreExecute - invoked in UI thread before the task is executed.this step normally used to to setup task an showing progress bar.
  • doInBackground - executed in the background thread to do things like network downloads.
  • onProgressUpdate - executed in the main thread when publishProgress is called from doInBackground.
  • onPostExecute - executed in the main thread to do things like set image views.

Written by

SDE | Ex-FrontBench | Blogger. I write about Startup, Self-Improvement, JavaScript, React and Node.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store