Android – How to handle an AsyncTask during Screen Rotation

androidandroid-asynctaskscreen-rotation

I read a lot on how to save my instance state or how to deal with my activity getting destroyed during screen rotation.

There seem to be a lot of possibilities but I haven't figured out which one works best for retrieving results of an AsyncTask.

I have some AsyncTasks that are simply started again and call the isFinishing() method of the activity and if the activity is finishing they wont update anything.

The problem is that I have one Task that does a request to a web service that can fail or succeed and restarting the task would result in a financial loss for the user.

How would you solve this? What are the advantages or disadvantages of the possible solutions?

Best Answer

You can check out how I handle AsyncTasks and orientation changes at code.google.com/p/shelves. There are various ways to do it, the one I chose in this app is to cancel any currently running task, save its state and start a new one with the saved state when the new Activity is created. It's easy to do, it works well and as a bonus it takes care of stopping your tasks when the user leaves the app.

You can also use onRetainNonConfigurationInstance() to pass your AsyncTask to the new Activity (be careful about not leaking the previous Activity this way though.)