Search code examples
androidandroid-activityandroid-serviceandroid-lifecycle

Android activity and foreground service - general question


This is a general question about the Android lifecycle for services and activities. I am not trying to solve a specific problem, just understand the mechanisms better to help with a design.

I believe Android can kill off an activity any time it likes, such as if memory is short and it is not the foreground activity. Doesn't necessarily call onDestroy() either (for some reason). It can do the same with services, but it is less likely - tries to keep services going.

Say I have an activity that starts up a foreground service. The service needs to inform the activity of some asynchronous events, and to do that the activity implements a specific interface, passes a reference of itself to the service, on which some interface method can be called by the service - ie a listener.

The activity goes into the background, and Android decides to kill it. But the service has a reference to it. So what happens to the activity? Presumably it cannot be garbage collected as there is a live reference to it in the service? Does this mean the service keeps the activity alive? One could clean up the listener in onDestroy(), but not if it isn't called.


Solution

  • It doesn't work like this. Generally speaking, Android doesn't kill off individual components (like Activity or Service). It just kills the OS process hosting the entire application. In this case all the activities and services will get killed off, as well as the VM. Unless you specify otherwise, all activities and services of an application are hosted inside the same VM in the same OS process.