Question

In answering a question here on SO about when onDestroy is called what appears to be an inconsistency in the Android docs arose.

According to the android docs regarding the task and backstack

"When the user presses the Back button, the current activity is popped from the top of the stack (the activity is destroyed) and the previous activity resumes (the previous state of its UI is restored). "

However at the same time, the android lifecycle suggests that activities are not automatically destroyed but rather paused if the UI is partially hidden, stopped if the UI is totally hidden, and destroyed only if the system is low on resources.

These are two opposite positions. So my questions is - which is it?

Shout out to @Raghunandan for going back and forth with me in comments for a while. Hopefully we will get an answer.

Was it helpful?

Solution 2

There is no contradiction in these two statements.

onDestroy is called when you press BACK unless you override onBackPressed not to call finish() or do a strange thing of overriding finish and not calling super.finish().

If you don't stop the call to Activity.finish, onDestroy is always called.

The other statement speaks nothing about pressing BACK and I can find nowhere under the link you have provided here that

and destroyed only if the system is low on resources.

Additinally to onDestroy being called when app is low on resources (which strangely doesn't happen on my phone; I get OOM) it is called when 20 other Activities globally (from all applications) are started after this one.

I also encouarge you to check out yet another answer on when onDestroy is called again for a real reason of onDestroy not being called.

OTHER TIPS

They are both correct in their context. Maybe the lifecycle should say "destroyed only if system is low on resources OR it is popped form the stack".

Consider this for example. You start with activity A, then start activity B from A, then start activity C from B.

  • Now both A and B are paused and stopped, but not destroyed.
  • If C is heavy on resources, A or B may be destroyed.

Now press Back button from Activity C, you are back to Activity B

  • Activity C is paused, stopped and destroyed .

Now press Back button again, you are back to Activity A

  • Activity B is paused, stopped, and destroyed

System tries to keep all the activity instances so they can be re-opened quickly. But when an activity is popped from the stack, there is no way for user to re-open them in future, at least not the same instance.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top