androidandroid-serviceandroid-lifecycleactivity-lifecycleandroid-memory

Understanding the Life cycle of Activity and Service


Suppose I have multiple activities say Screen A(Main Screen) & Screen B.

Screen A opens Screen B and then Screen B starts a service which sends updates to Screen B. Now when the user minimizes the app and the service is running and since Android OS is short of memory then it clears the App.

Now I have two question

1) Does the Android OS clear the memory of the whole app (Screen A & Screen B) or only my Screen B?

2) Will my service also be cleared or will it continue to run? If it is cleared then can a foreground service with a notification help me to overcome this?

Any help would be grateful.


Solution

  • Now when the user minimizes the app and the service is running and since Android OS is short of memory then it clears the App.

    When Android is short on memory, it terminates a process.

    Does the Android OS clear the memory of the whole app (Screen A & Screen B) or only my Screen B?

    By default, your app uses a single process. So, when Android terminates your process, everything of your app goes away.

    Will my service also be cleared or will it continue to run?

    By default, your app uses a single process. So, when Android terminates your process, your service will also go away. Some developers elect to put their service in a separate process (via the android:process manifest attribute) to help the service stay around longer, but that makes your app a bit more difficult to build.

    If it is cleared then can a foreground service with a notification help me to overcome this?

    A foreground service makes it far less likely that Android will terminate that service's process to free up system RAM. However, you should only have a service running when it is actively delivering value to the user.