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 ::

  1. I am having different layouts for portrait & landscape so cannot use android:configChanges="keyboardHidden|orientation|screenSize" to restrict activity recreation.

  2. 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.

Answers


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.


Need Your Help

math operation (plus/minus) in js

javascript math

I have a simple function, that should generate 1000 different elements:

How would one secure a PHP script to make it only usable when bought?

php security license-key

I have read an answer to another question here on Stack Overflow. Let me first quote the incriminated part: