Asynchronous vs Synchronous task


Download android AsyncTask sample

Synchronized means "connected", or "dependent" in some way. In other words, two synchronous tasks must be aware of one another, and one must execute in some way that is dependent on the other. In most cases that means that one cannot start until the other has completed. Asynchronous means they are totally independent and neither one must consider the other in any way, either in initiation or in execution.

In android perspective, an asynchronous task is defined by a computation that runs on a background thread and whose result is published on the UI thread.


AsyncTask


AsyncTask is an abstract class provided by Android which we can use to perform heavy tasks in the background and keep the UI thread light which makes our application more responsive

Why AsyncTask?


Android application runs on a single. Due to single thread model of android applications, tasks that take long time to respond can make the application non responsive. To avoid this problem we use android AsyncTask.

When use AsyncTask?


We should use AsyncTask for sort task that takes only few seconds at the most to finish.

We should avoid using AsyncTask for heavy task that can take few minutes or hours. To perform heavy tasks in background on a dedicated thread and passing the results back to the UI thread we can use other android apis like Service, Executor, ThreadPoolExecutor and FutureTask.


Android AsyncTask


AsyncTask's generic types


Three types used by an asynchronous task are given below:

  1. Params : Parameter type that need to sent to the task for 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.

AsyncTask's methods and their order of execution


  1. onPreExecute() : This method invoked on the UI thread before the task is executed. This step is normally used to setup the task, for instance by showing a progress bar in the user interface.
  2. doInBackground(Params...) : This method invoked on the background thread immediately after onPreExecute() finishes executing. This step is used to perform background computation that can take a long time.
  3. onProgressUpdate(Progress...) : This method invoked on the UI thread after a call to publishProgress(Progress...). The timing of the execution is undefined.
  4. onPostExecute(Result) : This method invoked on the UI thread after the background computation finishes. The result of the background computation is passed to this step as a parameter.

Why use public sub-class of AsyncTask?


What I have seen, most of the beginners prefer to use an inner sub-class of AsyncTask over public sub-class of AsyncTask. Let's consider a case, suppose we have to add, edit, delete and get records for User from server in 4 different activities. If we use private inner sub-class of AsyncTask, in that case we need to write 4 sub-class of AsyncTask, 1 in each activity to handle it, and there will be redundancy of code.

In all these 4 operations, we have to request some url with some data and in response the server will retun some data.

A better approach to do this task is to write a public sub-class of AsyncTask. call execute method with url and data. When AsyncTask finished it task, it can send response data received from server to the Activity which has initiated the task.

To communicate between Activity and AsyncTask we can create an Interface and implement it in each activity where we need to do Async task. I've demonstarated how to communicate between Activity and AsyncTask in this tutorial example.

AsyncTask rules?


  1. The AsyncTask class must be loaded on the UI thread.
  2. The task instance must be created on the UI thread.
  3. execute(Params...) must be invoked on the UI thread.
  4. Never call onPreExecute(), onPostExecute(Result), doInBackground(Params...), onProgressUpdate(Progress...) manually.
  5. The task can be executed only once (an exception will be thrown if a second execution is attempted.)

Example


In this example we will implement an AsyncTask that makes a process to go to sleep for a given period of time as set by the user, once task finished it will respond to a method of UI thread.

Step 1: Create a new project in Android Studio and name it AsyncTask Example.

Step 2:Open res -> drawable -> activity_main.xml and replace the code with code of activity_main.xml with the below given code.

activity_main.xml

Step 3:create a new package com.apnatutorials.model. Add a new Interface AsyncCommunicator inside this package. Replace the code of AsyncCommunicator.java with the below given code.

AsyncCommunicator.java

Step 4: Create a new class AsyncTaskHandler.java inside the package com.apnatutorials.model.Replace the code of AsyncTaskHandler.java with below given code.

AsyncTaskHandler.java

Step 5: Open MainActivity.java and replace its code with below given code.

MainActivity.java

Step 6:Open res -> values -> string.xml and replace its code with below given code.

activity_main.xml

Step 7:Clean and run your project to see the result.

Share & Like

Tutorial topics

About ApnaTutorials.com

ApnaTutorials.com is for Java, J2ee, Html5 and android developers. All tutorials are well explained and are easy to understand. We have tested every tutorials on our developement environment before posting it in public domain.