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
shows an AsyncTask
implementation as a static
inner class.
The task is returned in onRetainNonConfigurationInstance(), and
the hosting 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
old Activity
and onCreate()
of the new Activity
. Hence,
even though the actual background thread of the AsyncTask
may
continue to chug along during the orientation change, you do
not have to worry about onProgressUpdate()
or onPostExecute()
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
one in onCreate()
, your AsyncTask
will always have the right
Activity
to work from on the main application thread.
This does emphasize, though, that you want doInBackground()
of your AsyncTask
to be completely decoupled from the
Activity
. If you only touch your Activity
on the main application
thread, your AsyncTask
can survive the orientation change
intact.
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.