heading

heading

Monday, 27 January 2014

Android AsyncTask: When, Why and How to Use?

This post provides an overview of the Android AsyncTask class.  As always, I'll try my best to make things appear as simple as possible.  Without losing any further seconds, lets start!

AsyncTask, short form for Asynchronous Task is an abstract class that allows to perform background operations and publish the result on the UI thread without having the need to manipulate threads or handlers.  In simple words:

 AsyncTask enables proper and easy use of the UI thread.


When and Why to use AsyncTask?
Android implements a single thread model.  Whenever an Android application is launched, the system creates a "main" thread of execution for the application.  The main thread is also sometimes called the UI thread.  It is to be noted that the system does not create a separate thread for each instance of a component.

Consider the following situation. After entering his login details, a user clicks on the "Sign In" button. On button click, a request is sent to the server for authentication.  While awaiting for a response from the server, the screen will be non-responsive since Android is based on a single thread model.   These kind of situations is less likely desirable by a user.  Therefore we should avoid performing long running operations on the UI thread.

One solution to this issue might be to create a new thread and implement the famous run() method to perform this network call while keeping UI responsive.  However, if there is the need to make some changes on the UI based on the result of the operation performed. other issues may pop up.  To conclude:

 For file and network access operations, it is recommended to use the AsyncTask


How to use?
An asynchronous task is defined by 3 generic types:

AsyncTask<Params, Progress, Result>


AsyncTask has four steps:
  • onPreExecute() 
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.
  • do InBackground(Params...)
Invoked on the background thread immediately after onPreExecute() finishes executing.  This step is used to perform background computation that can take a long time.
  • onProgressUpdate(Progress...)
This method is used to display any form of progress in the user interface while the background computation is still executing.
  • onPostExecute(Result)
Invoke on the UI thread after the background computation finishes.  The result of the background computation is passed to this step as a parameter.

Below is an example that I retrieved from the official Android Developer's site.

private class DownloadFilesTask extends AsyncTask<URL, Integer, Long> {
     protected Long doInBackground(URL... urls) {
         int count = urls.length;
         long totalSize = 0;
         for (int i = 0; i < count; i++) {
             totalSize += Downloader.downloadFile(urls[i]);
             publishProgress((int) ((i / (float) count) * 100));
             // Escape early if cancel() is called
             if (isCancelled()) break;
         }
         return totalSize;
     }

     protected void onProgressUpdate(Integer... progress) {
         setProgressPercent(progress[0]);
     }

     protected void onPostExecute(Long result) {
         showDialog("Downloaded " + result + " bytes");
     }
 }
Once created, a task is executed very simply.

new DownloadFilesTask().execute(url1, url2, url3);

A working example of the AsyncTask can be found here.

No comments:

Post a Comment