Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android: how to stop service belonging to another application?

I have a few applications using a shared library that starts a service when the user opens one of the apps. Ideally only one instance of this service will be running regardless of how many of these apps are open.

For example, the user opens app "A" which starts the service. Then the user opens app "B" which detects that the service is running, stops it, and then restarts the service itself.

Is this something that can be accomplished in Android by running the service in it's own process, or by some other method?

like image 881
David Vail Avatar asked Jan 20 '26 05:01

David Vail


1 Answers

If:

  • The service is exported, and
  • Permissions allow you to talk to that service, and
  • You know how to craft an Intent to identify the service

then stopService() should work, assuming that the service can be stopped (e.g., there are no bound connections to it). stopService() is not limited to services in your own process.

The key here is security, ensuring that somehow you can stop the service and others cannot. That's not particularly easy, which is why you don't see this as a common pattern.

In your case, perhaps a better solution is not to stop the existing service and start a fresh one, but just to leave things alone, if your service instance is already running.

like image 130
CommonsWare Avatar answered Jan 22 '26 19:01

CommonsWare