Understanding of AsyncTask in Android


Basics of Android Thread

Android handles all the input events and tasks with a single thread and it is known as UI thread or Main thread. UI thread cannot handle concurrent operations. It only handles one event or operation at a time.

What will happen when you want to perform long running operation like download a file from Internet, Database operations, web-service calls? The application will hang until the corresponding operation is finished.The reason is simple as due to single thread model of Android till the time response is awaited our screen is non-responsive. So we should avoid performing long running operations on the UI thread.

To overcome this problem, we can create new thread to perform this long running operation so UI remains responsive.

But as we discussed Android follows single thread model and Android UI toolkit is not thread safe. If we need to update the UI based on the result of the long running operation, then this approach may lead issues.


What is AsyncTask

To overcome above mentioned issues Android framework has provides a dedicated class called ‘AsyncTask’ to handle the tasks/operations that need to be performed at the background asynchronously. AsyncTask is designed to be a helper class around Thread and Handler and does not constitute a generic threading framework.

Note: AsyncTask should ideally be used for operations that take few seconds. 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 FutureTask.


How to use AsyncTask class

To use AsyncTask you must subclass it. AsyncTask uses generics and varargs. The parameters are the following AsyncTask <Params, Progress, Result>.

AsyncTask is started via execute() method. AsyncTask class must be loaded on the UI thread and the task instance must be created on the UI thread.

The description of three generic types used in AsyncTask class is as follows:

Params: The type of the parameters sent to the task upon execution.
Progress: The type of the progress units published during the background computation.
Result: The type of the result of the background computation.


Override methods of AsyncTask

doInBackground:  Result doInBackground (Params... params)
Override this method to perform operation on a background thread.

onPostExecute:  void onPostExecute (Result result)
Runs after doInBackground method completes its processing. Result from doInBackground is passed to this method.

onPreExecute: void onPreExecute ()
Runs on UI thread before doInBackground method.

onProgressUpdate():void publishProgress (Progress... values)
Invoked from doInBackground(Params...) to publish updates on the UI thread while the background computation is still running.

Below Task diagram shows the callback methods flow when asynchronous task is executed from UI main thread:



Cancel Background Task

The task can be cancelled by invoking cancel(boolean) method. This will cause subsequent calls to isCancelled() to return true. After invoking this method, onCancelled(Object) method is called instead of onPostExecute() after doInBackground() returns.


Example of AsyncTask

Below are the code snipped of sample AsyncTask:
private class CustomAsyncTask extends AsyncTask<String, Integer, Double> {
        @Override
        protected String doInBackground(String... params) {
           // execution of long running operation on background thread
       }
      
        @Override
        protected void onPreExecute() {
        // Pre execute task on UI thread
        }

        @Override
        protected void onProgressUpdate(Integer... progress) {
        // Intermediate data update on UI thread
        }

        @Override
        protected void onPostExecute(Double result) {
            // Result of long running operation on UI thread
        }      
    }

In the above sample we’ve used CustomAsyncTask class to perform the AsyncTask operations. To execute this you have to call below code from your UI thread i.e. either from Activity/Fragment.

    new CustomAsyncTask ().execute(“TestTask”,10,2.0f);

To know more about AsyncTask refer Android developer link:

To find more interesting topics on Software development follow me at https://medium.com/@ankit.sinhal

You can also find my Android Applications on play store

Comments

Popular posts from this blog

Android O: Impact On Running Apps And Developer Viewpoint

Android Performance: Avoid using ENUM on Android

Smart way to update RecyclerView using DiffUtil