why is onDestroy() called when switching to another app

1.1k views Asked by At

Okay, I have read the section on the activity lifecycle, but there is something I still don't get. Why is onDestroy() being called in my app, when I am switching to another app that runs on my phone, or when I am hitting the home button.

From what I read, onPause() is being called when the app loses focus.

The system calls this method as the first indication that the user is leaving your activity (though it does not always mean the activity is being destroyed); it indicates that the activity is no longer in the foreground (though it may still be visible if the user is in multi-window mode). Use the onPause() method to pause or adjust operations that should not continue (or should continue in moderation) while the Activity is in the Paused state, and that you expect to resume shortly.

OnStop() I get as well:

When your activity is no longer visible to the user, it has entered the Stopped state, and the system invokes the onStop() callback. This may occur, for example, when a newly launched activity covers the entire screen. The system may also call onStop() when the activity has finished running, and is about to be terminated.

However, I don't get, why onDestroy() gets called as well.

onDestroy() is called before the activity is destroyed. The system invokes this callback either because: 1) the activity is finishing (due to the user completely dismissing the activity or due to finish() being called on the activity), or 2) the system is temporarily destroying the activity due to a configuration change (such as device rotation or multi-window mode).

First of all, I am not finishing my app, nor calling finish(). Secondly, there is no configuration change that I am aware of.

Hope someone can help.

FYI: My app extends Activity, uses multiple Threads, has a class that extends SurfaceView and implements SurfaceHolder.Callback, uses an IntentService and a ContentProvider. Apart from that, nothing special.

PS: When I switch off the screen, onDestroy() is not called.

PPS: I am not looking for a smelly workaround. I would like to understand what is happening and why.

2

There are 2 answers

0
MWB On BEST ANSWER

It turns out, I was using the android:noHistory flag in my manifest. Thanks to this post, I was able to solve my problem. Thanks @Alexis Contour!

1
SinaMN75 On

I'm not sure this is gonna help, but as far as I know when Android run out of memory, it will automatically run onDestory method of any Activity that is not visible on the screen.