In my app I have several AsyncTasks doing http requests. If a task fails I display a DialogFragment to the user.
ErrorDialogFragment newFragment = ErrorDialogFra
I've had the same issues before. A reasonably good answer I saw on a blog somewhere (I've forgotten) is as follows:
Give your AsyncTasks a reference to the current context. When your app is minimised/rotated, save your AsyncTasks using onRetainNonConfigurationInstance()
and getLastNonConfigurationInstance()
. Then when your app is restarted, in onCreate()
, you can check if there is an AsyncTask passed back from getLastNonConfigurationInstance()
. If there is, set it's context to the new context of your activity. Now your AsyncTask will be able to access the new Context and complete its task.
To be thorough, you probably also want to set your context to null
in your AsyncTasks before you save them using onRetainNonConfigurationInstance()
. Then in your AsyncTask, check if the Context is null before trying to do something using it. This will stop the app crashing if the AsyncTask tries to use the context while in the background.