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
AsyncTaskcontains aContextwhich is theActivitythat creates it. So it must be destroyed when theActivityis 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 aFutureand pass that to some implementation ofAsyncTaskthat only wait for theFutureto compute. - At a context switch we can destroy the
AsyncTaskwithout interrupting theFuturewhich we can hold on to. - When creating the new
Activitypost-context switch we create a new freshASyncTaskand give it the same still runningFuture.
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.
- Attach: CallableProgressDialogTask.java - The main java class that allows the creation of long running tasks that can survive context switches.
- Attach: DialogTaskTestActivity.java - An example of how to use the above class.