Android's AsyncTask sucks

12 נובמבר, 2011 -

  • English

I'm dabbling with Android development. Although I'm definitely getting to old to learn another UI platform (after Windows API, Win32, Visual BASIC, WinForms, WPF and, God have mercy on us all – Motif), but a man's gotta do what a man's gotta do.

As in any other UI platform (except VB 6), you can't perform lengthy operations from the  UI thread because the UI will freeze (except for VB 6, that doesn't really like threads, or responsive UIs…). The Google people created something called an AsyncTask. When you want to perform a lengthy operation, you fire up an AsyncTask from your UI thread, and all the threading details are taken care for you. You implement a doInBackground method that contains the background processing, and a onPostProcess method that will run in the UI thread after doInBackground is done. Very easy and rather elegant.

Unfortunately, it doesn't work well in real life. You see, in Android, you put your UI in Activities. An Activity is, well, an Activity that interacts with the user. It's similar to a Window in other  platforms – you fill the Activity with the controls you want and handle events as they occur. However, unlike any other platform I'm awareof, Activities die when you don't expect them to. For instance, if the user turns the phone from portrait to landscape – your Activity dies, and another is created.

The reasoning is to let Android take care of the new layouts for you – all the controls are recreated. Android takes care of copying their values (text the user entered prior to turning the phone), but it doesn't take care of anything else. It doesn't take care of your AsyncTasks, either. So if you run an AsyncTask that tries to notify the user after the processing is done, it does so through the Activity that created. By the time that AsyncTask is done, that Activity may not be around to be updated.

There's no easy way around this.

Enter BetterAsyncTask! Next time I'll describe a generic mechanism that handles it.

 

Zmbq.

One Response a “Android's AsyncTask sucks”


  1. Assaf Lavie Says:

    Total Android noob here, but I happened to attend a lecture on the subject ( http://www.meetup.com/The-Junction/events/31977992/ ) recently and the guy explained that there are also Services (iirc) that persist and you ought to use those for doing that sort of work.

Leave a comment!

  • Language

  • Blogroll

  • פוסטים אחרונים

  • Categories