Search code examples
androidandroid-studioservicebackground-service

Can i stop a service in Android Studio if I close the application that started it?


So I am a beginer in Android and I would like to create a background service that will change the wallpaper every 24 hours.

The app that i made has a button in the Main Activity the starts the service, and another button to stop the service.

What I would like to know is if i start the service, then i close the app, can i stop the service if I reopen the app and press the "Close Service" button ? I'm confused because I don't know if the app will know the reference to the active service.


Solution

  • This is the documentation of stopService(Intent service) in Context class.

    "Request that a given application service be stopped. If the service is not running, nothing happens. Otherwise it is stopped. Note that calls to startService() are not counted -- this stops the service no matter how many times it was started"

    So you would only need to call stopService(new Intent(this, YourService.class)) from your activity and it will stop all the instances of YourService