I was excited to see the introduction of the AsyncTask. Anything to make the division of UI / Background work easier is good in my book.

What bugged me was that I couldn’t see a way to keep a long running process alive during a context switch e.g. a layout orientation change. As far as I could see, the common way to ‘solve’ the problem was by stopping the process and then recreate it in the new Activity. This will work in some cases, but in others it won’t work. For example, a background task of creating a new user account on a website cannot be re-sent easily.

I spent a day and hacked out an alternative way of doing things. My approach was this.

  • We know that the AsyncTask contains a Context which is the Activity that creates it. So it must be destroyed when the Activity is destroyed e.g. at a context switch due to a screen orientation change.
  • Since we want to background task to continue ‘across’ a context switch we cannot define the background task within the AsyncTask. Instead we create a Future and pass that to some implementation of AsyncTask that only wait for the Future to compute.
  • At a context switch we can destroy the AsyncTask without interrupting the Future which we can hold on to.
  • When creating the new Activity post-context switch we create a new fresh ASyncTask and give it the same still running Future.

The easiest way to understand this is to see it in action. I hope you will find the files below useful. If you have any questions or suggestion, please do e-mail me at support{the at symbol}shodansoftware.com.