Android AsyncTask context behavior Android AsyncTask context behavior multithreading multithreading

Android AsyncTask context behavior


AsyncTask is not designed to be reused once an Activity has been torn down and restarted. The internal Handler object becomes stale, just like you stated. In the Shelves example by Romain Guy, he simple cancels any currently running AsyncTask's and then restarts new ones post-orientation change.

It is possible to hand off your Thread to the new Activity, but it adds a lot of plumbing. There is no generally agreed on way to do this, but you can read about my method here : http://foo.jasonhudgins.com/2010/03/simple-progressbar-tutorial.html


If you only need a context and won't use it for ui stuff you can simply pass the ApplicationContext to your AsyncTask.You often need the context for system resources, for example.

Don't try to update the UI from an AsyncTask and try to avoid handling configuration changes yourself as it can get messy. In order to update the UI you could register a Broadcast receiver and send a Broadcast.

You should also have the AsyncTask as a separate public class from the activity as mentioned above, it makes testing a lot easier. Unfortunately Android programming often reinforces bad practices and the official examples are not helping.


This is the type of thing that leads me to always prevent my Activity from being destroyed/recreated on orientation change.

To do so add this to your <Activity> tag in your manifest file:

android:configChanges="orientation|keyboardHidden" 

And override onConfigurationChanged in your Activity class:

@Overridepublic void onConfigurationChanged(final Configuration newConfig){    // Ignore orientation change to keep activity from restarting    super.onConfigurationChanged(newConfig);}