Android asynchronous tasks

Author: Eugeniy Marilev
Date of publication: 2014-05-06 10:42:14

Java-hardened developers or novice programmers when trying their hand at Android development to perform background tasks usually use the standard Java threads (Runnable interface and the class Thread). This method is, actually, an effective and proven, but there is a special base class AsyncTask to perform background tasks in the Android SDK.

Briefly let's take a look at all the features of this class, the situations in which it should be used, and, of course, advantages and disadvantages of using AsyncTask comparing to standard Java threads.

When is better to use AsyncTask instead of Runnable & Thread

This class is usually used to perform background tasks of an application, that in some way indicate the progress of a task in the application interface (GUI), or in any way access the GUI elements. If you try to implement an appeal to the GUI in a parallel flow , you will receive an error message , or if you're lucky - hang on of all application graphics while handling. This occurs because all of the graphics in Android is operated in main (GUI) thread and call to GUI must be performed from it. As previously described , it can be bypassed using pending messages of Handler class.

The functionality of AsyncTask

The charm of AsyncTask wrapper is that the logic of launching parallel stream and communication with the GUI thread using Handler is encapsulates in it. The class has an interface that looks like it:

/* UI Thread */
protected void onPreExecute()

- The method works in a GUI thread. It is launched before running the parallel thread.

/* UI Thread */
protected void onPostExecute() 

- The method works in a GUI thread. It is performed after a task is completed (the completion of the parallel flow).

/* UI Thread */
protected void onCancelled()

- The method works in a GUI thread. It is launched after the prior, possibly emergency quit of the parallel flow work.

/* UI Thread */
protected void onProgressUpdate(Progress... values)

- The method is called from a parallel stream with «publishProgress», and can communicate with the GUI thread. The purpose of this method is to show the user the progress of the background task.

/* Separated thread */
protected Result doInBackground(Params... params)

- The method, that is performed in a parallel flow, can communicate with the parallel flow only through «publishProgress» option. The insides of this method - it is the logic of a background task that runs in parallel flow.

It should be noted that the AsyncTask class is generic. The class has three parametric type: Params, Progress, Result, so if you create a background task class you will need to specify them:

MyAsyncTask extends AsyncTask
{
	    …
}

The immediate task is launched:

MyAsyncTask task = new MyAsyncTask();
task.execute();

The schedule task is launched:

MyAsyncTask task = new MyAsyncTask();
Handler handler = new Handler();
handler.postDelayed(task, 1000 * 3); //after 3 seconds

Advantages and disadvantages

Among the disadvantages of this class I would like to highlight:

  1. Too much use of parametric types.
  2. A cut-down cross-platform from the use of Android SDK ( the code can be run only in the Android OS).

Benefits, of course, are much bigger and more significant:

  1. Convenient and readable interface of class.
  2. Separation of processing a background process logic from GUI.
  3. Ability to manage time you start a background task

So , we try , because nothing is complicated . If we talk about specific examples - they will be available a little bit later ...

Need to develop an application for ANDROID? Go here.

Article comments
Comments:
Алексей Кропачёв
10\09\2012
Как пишет developer.android.com: AsyncTasks should ideally 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 pacakge such as Executor, ThreadPoolExecutor and FutureTask. Кроме того, не стоит забывать (для тех кто не знает, стоит взглянуть в) реализацию AsyncTask - это обёртка над ThreadPool в 5 потоков. Поэтому можно поспорить насчёт "весомых преимуществ" данного средства. Гораздо удобней, читабельней, кроссплатформенней и надёжней использовать Executor'ы для данных задач.
djvibegga_admin
10\09\2012
Алексей, а не хотите ли вы сделать статейку с использованием этих самых Executor'ов, в которой вы смогли бы раскрыть свой опыт в разработке под android?
Only logged users can leave comments.