Tips & Tricks: AsyncTask.

Hi Android developers,

This week in tips and tricks: AsyncTask.

A AsyncTask is a class that provides you an easy interface to create a new thread. It is recommended to use it by background tasks, like downloading through a internet connection.
From Honeycomb (SDK API level 11) it’s even mandatory to use Asynctask’s for internet connection downloads and if it’s not done it will force close the application. So it will be also for Ice Cream Sandwich.
Besides it’s mandatory it’s also really handy. You will take pressure from the UI Thread and it will be processed faster and parallel to the UI Thread.

You have to start with:

private class DownloadFilesTask extends AsyncTask<void, void, void>

There are five methods to implement which are:
The first method called in the AsyncTask, called on the UI thread. In this method you usually prepare the progressbar, if needed.

protected void onPreExecute() {

This is the method where is all the action. This method executes the time consuming tasks and publish the task progress, executed in background thread.

protected String doInBackground(String... params) {
    // perform Long time consuming operation
    return null;

Method that updates the progress of the AsyncTask, run on the UI thread. This is where you update the progressbar.

protected void onProgressUpdate(String... progress) {

The final method that gets called after doInBackground finishes, here we can update the UI with the results of the AsyncTask, like removing the progressbar.

protected void onPostExecute(String unused) {
    try {
    } catch (Exception e){
        Log.e("APP_NAME","Unknown exception caught: " + e.getMessage());

This method gets called if the AsyncTask.cancel() methods is called, terminating the execution of the AsyncTask.

protected void onCancelled() {

To execute it just use:

new DownloadFilesTask().execute(param1, param2);

As you can see the AsyncTask is easy to implement and the methods are really easy to use and understand. It is highly recommended to use AsyncTask for task that doesn’t have to update the UI Thread.

We use AsyncTask in Let Me Android That For You and Perka’s File Stash.

For more information:

PullesSon – Android

Honeycomb and Tegra 2

We are currently working on some Honeycomb (Android 3.x) project with Nvidia Tegra 2. So expect some BIG applications in the near future.