AsyncTask and Screen Rotation
In The Busy Coder’s Guide to Android Development Version 3.1,
I added a section on how to handle orientation changes and
AsyncTask. The sample project
AsyncTask implementation as a
static inner class.
The task is returned in onRetainNonConfigurationInstance(), and
Activity is responsible for making sure the
AsyncTask knew the right
Activity instance to use, before
and after the orientation change.
And the code works.
But, until today, I didn’t quite know why.
It turns out that Android will not process messages off of the
message queue between
onRetainNonConfigurationInstance() of the
onCreate() of the new
even though the actual background thread of the
continue to chug along during the orientation change, you do
not have to worry about
being called during the transition period. And, if you use the
pattern described in the book and demonstrated in the above
code sample — detaching from the old activity in
onRetainNonConfigurationInstance() and attaching to the new
AsyncTask will always have the right
Activity to work from on the main application thread.
This does emphasize, though, that you want
AsyncTask to be completely decoupled from the
Activity. If you only touch your
Activity on the main application
AsyncTask can survive the orientation change
As Ms. Hackborn points out, this is not only for orientation changes. It used to be that the only likely configuration change “on the fly” was an orientation change. But now we have car and desk docks that trigger configuration changes, etc.Tweet