Fragments are recreated automatically when their parent Activity
or Fragment
is recreated. If the child fragments were related to state that is not retained between instances of their parent, when should I remove them?
- In the parent fragment's
onDestroy()
: unreliable sinceonDestroy()
might not be called. - In the parent fragment's
onCreate()
: presumably the children have not yet been created at this point. - Some other lifecycle method that is guaranteed to be called after the children have been recreated and added. Is
onViewStateRestored(...)
the right place for this?
In case my question isn't clear, here's an example:
An Activity
has a Fragment
which contains an asynchronous operation. The fragment would normally cancel this task in onDestroy()
. But if the fragment is destroyed without onDestroy()
being called, it may later find itself recreated with the background task uninitialized. In that case, it should remove its old progress dialog. When should it test for this condition?
Edit: When the user swipes the app out of recents, all its components are destroyed without calls to onDestroy()
. But in that case, the fragment hierarchy is apparently obliterated along with the rest of the app. When the app is restarted, the fragment is not automatically recreated, so I don't have to worry about removing it.
When the fragment is destroyed because its host activity is put in the background and "don't keep activities" is turned on, the fragment is automatically recreated. But in that case, it seems I can count on onDestroy()
being called.
My concern is what happens when the app is killed to free memory. Hopefully it will behave like swiping from recents, where the fragment hierarchy is not restored. That would render my whole question moot. Can anyone confirm what happens in that case?