Android AsyncTask Tutorial with Example

By | June 11, 2019
AsyncTask in Android Tutorial Example

What is background AsyncTask in Android ?

AsyncTask is an abstract Android class which helps the Android applications to handle the Main UI thread in efficient way. AsyncTask is a Asynchronous Task .it is allows in background synchronize in main thread.

AsyncTask class allows us to perform long lasting tasks/background operations and show the result on the UI thread without affecting the main thread. You can use this class to create background process but its not display and its display result in UI main thread.

AsyncTask to perform the heavy tasks in background on a dedicated thread and passing the results back to the UI thread. In this class is override at least one method i.e doInBackground(Params).

This class is used to do background operations that will update the UI(user interface). mostly used it for short operations that will not effect on our main thread.

AsyncTask is First of called onPreExecute() method.then second is called doInBackground() and then last method is called onPostExecute() to update UI.

Methods of AsyncTask in Android

onPreExecute() : This method is used to contains the code which is executed before the background processing this method is first call in AsyncTask.

doInBackground() : This method is used to send results multiple times to the UI thread by publishProgress() method. To notify that the background processing has been completed we just need to use the return statements. In this method to process in this method is second called in AsyncTask.

onPostExecute() : This method is used to called after doInBackground method completes processing. Result from doInBackground is passed to this method. In this method is completed background process then display result in this method to send UI data.In this Method is last time called in AsyncTask.

onProgressUpdate() : This method is used to receives progress updates from doInBackground method, which is published via publishProgress method, and this method can use this progress update to update the UI thread.

Example of AsyncTask in Android

Create activity_main.xml File Follow this code.

Create File Follow this Code.

In this Example of I have created ProgressBar and button and create MyTask class. in this class extends of AsyncTask and then pass the parameter.First Parameter is URL to download file. Second Parameter is ProgressValue then third parameter is is defined in this example.

Now in this example you can click on start Download to progress bar is start and then print the percentage. in this task is background process. it is simple AsyncTask example.