3

I am in need of stop all the service which I used in my app when I killed or remove from my recent apps in android. Is there any possible to determine ?

  • Welcome to Stack Overflow! You should put code in your question for us to get a full picture as to what is going on. – Qwerp-Derp Mar 31 '17 at 07:29
  • If you app is killed all your services are also killed (spots). Usually problem is to restart service after restart of app. :) – LunaVulpo Mar 31 '17 at 07:30
  • call stopService() method on onDestroy() method of Acitivity. – DkThakur Mar 31 '17 at 07:31
  • Just I am asking my requirement to achieve in my app. Not yet started write the code. I know well onDestroy not getting called while kill or remove the app from recent. So I need some alternate way to determine the app is killed. – Sundaramoorthy J Mar 31 '17 at 07:32
  • so maybe you need a receiver for system broadcast? look in to: https://chromium.googlesource.com/android_tools/+/febed84a3a3cb7c2cb80d580d79c31e22e9643a5/sdk/platforms/android-23/data/broadcast_actions.txt maybe you find right for kill app – LunaVulpo Mar 31 '17 at 07:50

1 Answers1

5

The Service class has an onTaskRemoved() method which is triggered when the app is removed from the recent apps.

There the Service can call stopSelf() to shut itself down.

As in:

/**
 * This is called if the service is currently running and the user has
 * removed a task that comes from the service's application.  If you have
 * set {@link ServiceInfo#FLAG_STOP_WITH_TASK ServiceInfo.FLAG_STOP_WITH_TASK}
 * then you will not receive this callback; instead, the service will simply
 * be stopped.
 *
 * @param rootIntent The original root Intent that was used to launch
 *                   the task that is being removed.
 */
@Override
public void onTaskRemoved(Intent rootIntent) {
    super.onTaskRemoved(rootIntent);
    stopSelf();
}

And then there's the exception that if the FLAG_STOP_WITH_TASK flag is used this callback isn't triggered, but the Service is automatically stopped when the app is killed. You may want to use onTaskRemoved() if you need to do something in the Service before finally stopping it.

Markus Kauppinen
  • 3,025
  • 4
  • 20
  • 30
  • Would calling **android.os.Process.killProcess** accomplish the same thing? – IgorGanapolsky Oct 25 '17 at 20:57
  • Probably. I haven't used that. There's [some discussion whether it's a good or a bad idea](https://stackoverflow.com/questions/11035328/why-calling-process-killprocessprocess-mypid-is-a-bad-idea) here on StackOveflow. – Markus Kauppinen Oct 26 '17 at 16:13