Activity lifecycle for non-foreground activity

168 Views Asked by At

My app has a main activity and occasionally on some user action it opens up another activity (and remains in the activity stack).

My understanding is, Android, if needed, can decide to kill the main activity when it's in background though the currently visible one will be unharmed. I am pretty sure I have seen this phenomenon in past (2-3 years back).

Here are the questions -

  • Under what conditions Android might decide to kill the background activity though the app is in foreground?
  • Does some specific version of Android/vendors have more chances of doing this than the other?
  • If I remember correctly, in such cases activity's onStop may or may not be called. Is this assumption right?
2

There are 2 best solutions below

2
On BEST ANSWER

My understanding is, Android, if needed, can decide to kill the main activity

There's no main activity concept in Android. Your app can be killed as whole or some unused elements can be garbage collected.

I am pretty sure I have seen this phenomenon

This is not a phenomenon but normal Android system behavior.

Under what conditions Android might decide to kill the background activity though the app is in foreground?

Does not matter really. All you need to bother is that you can be killed/restarted and knowing that all you need to do is to ensure your data can survive.

Does some specific version of Android/vendors have more chances of doing this than the other?

Again the same - it does not matter. Ensure your app handles such case correctly and that's it.

If I remember correctly, in such cases activity's onStop may or may not be called. Is this assumption right?

No, unless your process is really killed, not garbage collected.

2
On

If an activity is completely obscured by another activity, it is stopped. It still retains all state and member information, however, it is no longer visible to the user so its window is hidden and it will often be killed by the system when memory is needed elsewhere.

To answer your question your MainActivity will be stopped as soon as your new activity is launched,

you should read up on the activity lifecycle: https://developer.android.com/reference/android/app/Activity.html