0

I'm working on Android 12 and I try to (force) kill my foreground service.

I can kill it from adb by the command: adb shell force-stop "my service"

But when I do it programmatically (as was suggested by How to kill an application with all its activities?) the OS restarts the service after it was killed.

That's my code which kill the service but then is initialized by the Android OS:

                android.os.Process.killProcess(android.os.Process.myPid());
                System.exit(0);

Any idea?

Thanks

Amiad
  • 361
  • 1
  • 2
  • 7

2 Answers2

0

While the kill is an abnormal termination and the OS restarts the service, the following code is a clean exit from the application similar to force-stop:

finishAffinity(); System.exit(0);

Amiad
  • 361
  • 1
  • 2
  • 7
  • `finishAffinity()` is only relevant for activities. It does nothing to services. Calling `System.exit()` is basically intentionally crashing your OS process. This is not the same as force-stop, because if you force-stop an app, it will never run again until the user manually starts it. – David Wasser May 15 '23 at 14:35
0

Android is restarting your Service because of whatever the Service returned from onStartCommand(). This value tells Android what to do if the Service is killed. You've probably returned START_STICKY which will cause Android to restart the Service if it is killed (for whatever reason) while started. If you don't want that to happen, return START_NOT_STICKY or some other value that won't cause Android to restart your Service. Also, as @CommonsWare suggested, you can just call stopService() to stop your Service. Killing the OS process is a very harsh (and not recommended) way to stop a running Service.

David Wasser
  • 93,459
  • 16
  • 209
  • 274