Search code examples
androidserviceandroid-activitysystemkill-process

How to avoid system killing service when application/activity is killed


I have an app with one activity and one service. If I kill the activity while the service is running it gets killed too. It is very important for me that the service doesn't get killed. How to make that when the system kills (or I kill it by clearing the "Recent apps" list) the activity the service still remains active until it finishes its job? Thanks in advance!


Solution

  • It is very important for me that the service doesn't get killed

    Your processes can be killed at any time, for any reason, based on user activity (recent tasks list, a third-party task manager, "Force Stop" in Settings, etc.) or based on OS needs (system RAM is getting low). You cannot prevent this.

    You can take some steps to minimize the odds of the OS deciding on its own to terminate your process, such as using startForeground() on the service, but this does block the user from doing what the user wants with your app's process.

    I'm displaying a window from that service so if the service stops then the window disappears.

    Presumably, the user wants your window to disappear if the user is explicitly getting rid of your app via the recent tasks list, a task manager, etc. You are certainly welcome to advise users in your documentation of any negative effects that this will have.

    You are also welcome to experiment with having that service be in a separate process. My understanding is that this will not help with the recent-tasks list on Android 4.4, though it might on earlier versions of Android. Whether this helps with third-party task managers probably depends on the manager, and this should not help with "Force Stop" from settings. It also means that you will have to deal with IPC, increased system RAM consumption while your main and service processes are both running, etc.