Thursday, February 25, 2010

Programming Android: non-documented problems with AsyncTask

AsyncTask class is very handy to execute one-time operations in the threads separate from main UI thread  and communicate results back to it. However I figured out that AsyncTask must be used with caution as it’s behavior may unexpectedly change after invocation of some of its methods.

Scenario #1: Methods onProgressUpdate() and onPostExecute() are not called as expected

Expected behavior: AsyncTask class methods  onPostExecute() and  onProgressUpdate() are called during and after task execution. E.g.  method onProgressUpdate() is invoked in the main UI thread whenever publishProgress() is called  inside doInBackground() worker method; Method onProgressUpdate() is invoked in the main UI thread upon doInBackground() method completion;

Problem synopsis: Neither onPostExecute() nor onProgressUpdate() are not called at all or called all at once after completion of the task

Solution: This is happened when after starting AsyncTask execution one of the following methods was called: AsyncTask.get() or AsyncTask.getStatus(). Similar situation occurs  when AsyncTask is executed by JUnit test cases based on Android Testing Framework.

Currently I don’t have explanation why its happens and how to solve this, but I’m still researching it. At least I know what to do for preventing the issue.

[Via http://vkroz.wordpress.com]

No comments:

Post a Comment