Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is onDestroy() guaranteed to be called for Fragments?

I know for an Activity onDestroy(...) is not guaranteed to be called. According to the docs,

There are situations where the system will simply kill the activity's hosting process without >calling this method (or any others) in it, so it should not be used to do things that are >intended to remain around after the process goes away.

Does this also apply to Fragments? Nothing is stated in the docs but just want to make sure.

like image 733
Chris Arriola Avatar asked Feb 10 '14 03:02

Chris Arriola


People also ask

Is onDestroy guaranteed?

Android Activity onDestroy() is not always called and if called only part of the code is executed. Save this question. Show activity on this post. onDestroy() is not always called.

What happens when onDestroy is called?

If onDestroy() is called as the result of a configuration change, the system immediately creates a new activity instance and then calls onCreate( ) on that new instance in the new configuration.

Why is it necessary to use the onDestroy method?

onDestroy() is a method called by the framework when your activity is closing down. It is called to allow your activity to do any shut-down operations it may wish to do.

What method is automatically invoked when a fragment is instantiated?

Fragment and View STARTED When the fragment becomes STARTED , the onStart() callback is invoked.


1 Answers

I believe that Fragment's onDestroy() is not guaranteed to be called just as Activity's.

In Activity's performDestroy():

 final void performDestroy() {
    mDestroyed = true;
    mWindow.destroy();
    mFragments.dispatchDestroy();
    onDestroy();
    if (mLoaderManager != null) {
        mLoaderManager.doDestroy();
    }
}

where mFragments.dispatchDestroy() will finally call fragments onDestroy(), if you digg into the source. So, if Activity's onDestroy() not called, fragment's onDestroy() won't be called.

And there's some other links:

fragment lifecycle: when "ondestroy" and "ondestroyview" are not called?

Android fragments lifecycle onStop, onDestroyView, onDestroy and onDetach

like image 50
bladefury Avatar answered Sep 28 '22 03:09

bladefury