Async task within fragments during screen oreintation
How to retain async task during screen oreintation. I have searched it much but not found any elegant solution to it.
What are my issues ::
I am having different layouts for portrait & landscape so cannot use android:configChanges="keyboardHidden|orientation|screenSize" to restrict activity recreation.
I cannot use Fragment.setRetainInstance(boolean) as I am having nested fragments so I am adding fragments to back stack using addToBackStack()
In this situation :
onCreate() and onDestroy() are not called. This is metioned in the API docs.
A bundle passed from onSaveInstanceState() is not received in onCreateView(). The passed-in Bundle is null. So I will not get the saved instance of the activity
How to retain a async task in fragments to avoid crashing on orientation change.
Or is there any other way for performing asynchronous task.
If you can't use a retain instance of a Fragment you should use a Service or an IntentService to run your Task. The idea of a Service is that it keep processing independent what happens in an Activity. Because you didn't say someething about the Tasks work, decide which one fits best to your App.
To run an AsyncTask in an Activity is usually a bad idea, because of the fact that the Activity can be destroyed by the system or while orientation changes. Now there are plenty of work arounds out there to deal with this, like the retain Fragment approach. But these are having some disadvantages, like the onSaveInstanceState() point you noted. And all work arounds deal with the same thing: keeping the reference.
I don't know why it's not very popular to use a Service, which is the easiest way to run an async task (of any kind) without getting headaches while thinking about how to hold a reference to it.
Alternatively, you could try launching your AsyncTask in its own task (see Intent.FLAG_ACTIVITY_NEW_TASK) so its lifecycle becomes independent of your Activity being destroyed, then recreated.
You can then comunicate with using a Handler for retrieving results and/or progress.