How to stop foregroundservice when task is removed?



I am trying to stop the service when the app is exited, however it continues to run for a minute or two.

This is the code I rely on:

override fun onTaskRemoved(rootIntent: Intent?) {

if I were to stop it manually with a button click and then exit the app everything works. I can see that the process exits immediately in android studio.

Button listener in MainActivity:

binding.mainBtn.setOnClickListener {
    isConnected = if(!isConnected && checkPermission()) {
    } else {

The manifest file looks like this:



Well, the ‘stop app’ thingy in android studio is not grayed out, I can continue to profile the app for like one or two minutes before it terminates

Your process is still running. There is no requirement that swiping a task off of the overview screen will terminate your process, or that it will do so in all cases.

In both cases stopService is run and I expect the same behavior

Alas, that is an unrealistic expectation.

Many devices will terminate your app’s process when the user swipes the task off of the overview screen, if either:

  • You do not have a foreground service running at the time, or
  • You do, but you stop that foreground service in onTaskRemoved()

However, that is not guaranteed. Other patterns include what OnePlus is doing, where your process stays running even if you stop the foreground service in onTaskRemoved(). That is OnePlus’ decision to make, as it is their device. Similarly, other manufacturers can do whatever they want. We have seen manufacturers terminate your app’s process even if you have a foreground service running. We have seen manufacturers do the equivalent of "Force Stop" in Settings, so all your app’s alarms and jobs get wiped out (among other effects). And so on.

On the whole, try to make few assumptions about app behavior when the user swipes the task off the overview screen.

Answered By – CommonsWare

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave A Reply

Your email address will not be published.

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Accept Read More