using android AsyncTask

While coding for CuTewit, I have refined the multi threading framework of the app couple of times. In this post I am documenting what I have learnt from the experiences. The intial part of the post, describes the old way of coding asynchronous tasks for Android, while the later part talks about how to make use of android.os.AsyncTask and my enhancements to it.

If you have been coding for mobile platforms you must know the importance of multi-threading. Network access is a very basic requirement of nearly all mobile apps. So when the app is fetching data over network (or doing any high latency task), the GUI’s main loop can’t be left unattended. That’s why time consuming jobs have to be performed in a separate thread.

Android GUI is no different. If you want to see the basic approach taken to solve this problem, then read this post. I used a similar approach in early releases of CuTewit. It was somewhat similar to the AsyncTwitter implementation that Twitter4J had. As you will find out after going through the article, that it’s not the simplest way to code a multi-threaded app. The big problem I faced with that design was, the background task is not represented by a well defined entity. So whenever one has to add a new background task, one has to make code changes at many places.

Another approach that was available was the UserTask example. This eventually became part of the platform and is available as android.os.AsyncTask.

AsyncTask makes the job of coding asynchronous tasks very manageable. You can code your asynchronous task as a derivative of AsyncTask and mainly have to override two methods. One method (onPostExecute) runs on the GUI thread, while the other methods runs on the background thread (doInBackground). These are the only two places where you have to add code, when it comes to coding a new async task.

Under the hoods, AsyncTask implements a similar strategy as described in first link above (using MessageHandler to communicate with GUI thread). AsyncTask maintains a static threadpool, which contains a preset number of threads. The Async tasks that you schedule are executed on one of these threads. You as an app programmer shouldn’t make any assumptions about the size of the threadpool. You must use proper thread-safe techniques while coding your app. However, I observed something that made me dive into the AsyncTask’s thread pool implementation. I was scheduling more than one AsyncTask in the background and I found that they were not executing simultaneously but one after the other (they were still executing in a background thread, but it appeared to be the only thread). After a while I figured the threadpool is hardcoded to have only single background thread. After a discussion on the mailing list, it turned out as a bug and will be fixed in future drop. In the meanwhile I went ahead with the workaround. Since the AsyncTask is a single file implementation, I just copied the into my project (named it and made changes so that I could get 4 concurrent background threads to execute my background tasks. You can check the discussion for exact details of the workaround.

Starting from CuTewit release 2.0, I have extended the (i.e. in my project) to simplify my app code and avoid code duplication at some places. Here is what I have learnt from the experience, maybe you will find it useful too.

The additions I did to AsyncTask code, are basically the following two:
1. Payload
2. Retry logic

Let me now elaborate.

1. Payload

The principal difference between a synchronous and an asynchronous task is the flow of control. While executing a synchronous task (i.e. a function call), the control doesn’t return until the task is finished. Once it is finished control returns to the same place in the code, from where the program can resume now processing the results of the synchronous task. In asynchronous tasks, the control returns to the calling code immediately, even before the async task has finished (or maybe even before it has started). So when the async task actually finishes, we need to make provision for processing its results. Thus in addition to the arguments and result, we need to pass the async task some extra entities. I like to model this as a payload of async task.

A payload is an object, that contains 1) the input arguments for the task, 2) place to store result of the task, 3) references to objects which can process the result of the task after it has finished, 4) optional retry mechanism. In my case I use the same AsyncTask class for doing numerous slightly varying tasks; so I also like to pass 5) a task type in the payload.

After a while I found that the nature of Payload class is generic. Irrespective of the app-specific derivative of AsyncTask, the Payload members remain the same. So I defined it as an internal class of the AsyncTask itself.

**public** **static** **class** Payload  
  **public** **int** taskType;        // task type  
  **public** Object data;         // input args and result processing objects  
  **public** Object result;       // result holding object  
  **public** **int** retryCount = 0;  // retry count  
  **public** Payload(**int** taskType, Object data) {  
      **this**.taskType = taskType;  
      **this**.data = data;  
  **public** Payload(**int** taskType, Object data, **int** retryCount) {  
      **this**.taskType = taskType;  
      **this**.data = data;  
      **this**.retryCount = retryCount;  
  **public** **boolean** retry() {  
      **if**(retryCount > 0) {  
          **new** MyTask().execute(**this**);  
          **return** true;  
      **return** false;  

Payload object is what you will pass to AsyncTask’s execute() (which is passed to doInBackground). And payload object is what you return from the doInBackground() too. So now the derivative of AsyncTask looks as follows.

**public** **class** MyTask  
 **extends** AsyncTask<AsyncTask.Payload, String, AsyncTask.Payload>  
 **public** **void** onPostExecute(AsyncTask.Payload payload)  
     Object[] data = (Object[]);  
     // ...  
     **case** TASK_1:  
     **case** TASK_2:  
 **public** AsyncTask.Payload doInBackground(AsyncTask.Payload... params)  
     AsyncTask.Payload payload = params[0];  
     Object[] data = (Object[]);  
     // ...  
     **case** TASK_1:  
         payload.result = // ...  
     **case** TASK_2:  
     **return** payload;  

2. Retry logic

One advantage that async task has over sync task is that in case of failure, it can be retried transparently. So in case the task fails (indicated by payload.result being null); it can be reattempted with the same payload with the retry count decremented by 1.




Types of Art

Dimensions of Idea communication


Lessons for Game designers from "Structure of Scientific Revolutions"

Bicycle pedals

Insanity and Software

Playing games, Doing Mathematics

Violet end of spectrum

Vipassana Meditation

Why gamers like pixelated games


Collecting Vs Hoarding Netflix

Game Design tip for Programmers - Less Automation

Review Ghost In The Shell - The blinds scene

Why Electron is the best development platform?

Project Dialog


Don't Panic

The Entanglement Pattern

The flying cars analogy

Road Trip of Atlantic Canada

Having done attitude


Before fixing performance issues

No Exams, Yes Video games

Podcasts Français


Quotable Quotes



Uruguay's President

New rules for Formula 1

Software Engineering Code of Ethics and Professional Practice

Something's missing


Coffeescript: To switch or not to switch

Water from air

The single most reason that keeps me using Vim

Time travel fiction

When your git branch diverges from your remote

Something like Olivia - John Mayer

Online courses - New technology, Old rules

Kelsey Grammer is spectacular

Why Patriotism doesn't make sense

Why sea steading is important to pursue?


Rolling back latest git commit

Google Lunar X Prize

iTunes Download stopped (err =9006)

Good essay on user centric software design

Why we need to explore Seasteading?


Master pieces from screen

How to write interactive CLI utility in node.js

The Gods Themselves by Isaac Asimov

Why OpenGL ES is so hard?

How to print stack trace anywhere in Javascript

It's not fair to compare Android with Internet Explorer

How to debug WebWorker threads?

Why can't I criticize Government if I don't vote? I sure can.

Elon Musk quote

Don't label yourself

Why the hi-tech minds are writing Social apps?

Truce with exercise

JavaScript is the next C

Ever growing todo list is a good sign for creative projects

Lesser women in tech... So what?

HTML5 offline cache - use swapCache carefully

How Wikipedia and Flattr can together change the World


Discovering LastPass

Functional programming in Javascipt using Underscore.js

Youtube ETA - Chrome extension

Why secure airports when it's planes that fly?

Mac book red light audio jack problem on Linux

How to save HTML5 canvas image to Google App Engine

Why don't they publish eBooks for free but with embedded ads?

Silicon Valley and Hi-tech

Reality distortion field around

Indirect experiments

Music sharing

ReaderScope 2.0.6 - Find Comments

ReaderScope 2.0

predictably irrational

ReaderScope upcoming changes


Why "Open" is not the first concern of user?

Mutt, Gmail, gdata, notify-send: A Perfect Email solution

Are you the Matt Damon of your game?

ReaderScope 1.9 - OAuth

New app "Find Comments"


ReaderScope 1.8.{2,3} - new authentication and global share

Portable apps for iPhone, Android, Pre, n900 - Can Processing.js help?

ReaderScope 1.8.1 - rethinking features

ReaderScope 1.8 - Random

Android fragmentation : How big a deal is it?

on Dropbox


ReaderScope v1.7 - Widget, new Icons and .... Ads

on Git: tips for SVN users and Git in Dropbox cloud

How to do an online IDE for Android app development

Anti Asserts

Bono's top ten list

Make Android speak your Twits with "TwitSpeak"


Reality of colors

Talking Twitter client

ReaderScope 1.5 - quicker, better, prettier

Preview android.R.drawable.* images

Is definition of "Evil" changing?

on Music: Battle Studies

ReaderScope 1.4 (with a Theme Pack)

On Chrome OS

Black on White

Android AsyncTask template

The AND-OR problem of laptop and mobile phone

ReaderScope v1.3.3 - offline podcasts

ReaderScope v1.3.2 - Social Channels

ReaderScope v1.3 - Beyond Google Reader

Frets on Fire for Maemo - Update

ReaderScope 1.2.7 - Podcasts, Expanded View

Sprint HTC Hero problems with ReaderScope

ReaderScope 1.2.3 - Search

ReaderScope 1.2.1 - Auto Login

ReaderScope v1.2

ReaderScope 1.1.3 - SDCard storage

Crash report for Android App

Wifi and Battery

ReaderScope 1.1.2

ReaderScope 1.1.1 quick-n-easy features

ReaderScope 1.1 - Social Beacons

ReaderScope 1.0.2 - making deep cache simple

ReaderScope 1.0.1

ReaderScope 1.0

Detecting HTC magic on Fedora

ReaderScope beta4 - offline fun

ReaderScope beta3 - Tweet the news

ReaderScope Beta2

ReaderScope beta1 is out

Intercepting Up/Down keys from bash script

Makeshift XML beautifier in python

HTC Magic (Indian version) - expectations and facts

using android AsyncTask

Android development with Vim + Eclim

Cutewit (preview)

Einstein's Dreams

Preprocessing the GUI

Evas + Inkface in v0.2.5

easy source

FoF - PyOpenGL = miniFoF (possibly for n810)

FoF update

Twitter client with inkface-pygame v0.2.2

Frets on Fire on Maemo 5 (Fremantle)

Static IP configuration on Fedora 10

Inkface+pygame v0.2.0

Smooth scrolling with Inkface+pygame

Inkface v0.2 update and automated GUI testing

Testing Android (Koolu Beta 3) on Openmoko Freerunner

Clutter animation paths with Inkscape+Inkface (v0.1.3)

Turning a page

Planning Inkface v0.2

Debian repository on Google App Engine

Inkface + Clutter

Inkface v0.1.2, Twitter-inkface client


Inkface update

Debugging python reference counts

Paul Graham nails it again!

Fedora 10 on MacBook 2,1

A great essay

Thanksgiving at Crater Lake

Digital SLR buyer's guide

more fun with notify-send

(k)ubuntu 8.10 - not ready for my home yet

Migrating to Google App Engine

Android opened - first looks inside

Has it started?

Inkface v0.1

Musical discovery of the week

Die Berlin-Affäre

aus Berlin

Inkface - SVG based GUI design

Script fun

Visualizing source code

OpenMoko photo tour

New connection with the past

George Carlin - favorite clip


80-20 rule

Python fun

OSiM'08 Berlin, Germany

Of games

"Wine" tasting

Today's slashdot and open source

Cost of Open Source

Lions for Lambs

Ubuntu reviewed

Flickr uploads from n810

Cringely and Paul Graham

Accelerometer brainstorming

Clutter Webkit

OSiM USA 2008 - Day 2

OSiM USA 2008 - Day 1

Google code

Gr8 commercial

OSiM USA 2008, see you there

OpenMoko, Android and a great hacking post

two great videos

Blog from nokia tablets


cool n770 hack


Colbie Caillat

Firefox 3 is brilliant!!!

XML RPC server inside apache mod_python

best effort technologies

coding Monalisa

formula of a horror movie

next desktop jump

The "Screen"

Nice review article on virtualization technologies

Once again... a quote from 'Troy'

Story of a random number

quotes from George Carlin

"from time import sleep"

Sea surfing under the Golden Gate

Trip videos


across two hours

What I read...

How do I backup to Amazon S3 storage service

Stranger than fiction

Gas prices... seems like big scam

Another nice quote

Hilarious nerd comment

Programming & Painting

Why do we like fiction?


If Harry Potter were a computer hacker ...

Gentoo, XGL, HGG

Henry Ford

VI - A capable IDE

New blog

Safari Bookshelf


Back to the L4


GCC 2.95 rpms

repeat (ps | grep) = filtered top

Halo fixed on ATI Mobility Radeon 9000

DirectX Installation Problem

Warning: const is a keyword in ANSI C

Not much on L4 front

Last two weeks


Stumbled on HURD

Installed HURD console

Make problem solved


Handy way to create stack trace