Search code examples
androidbuttonservicewidgetshutdown

How to use a homescreen widget button to shutdown a service?


I have a button whose WidgetProvider kicks off a service with a PendingIntent. That works just fine. How do I similarly attach an event handler to the button so that when it is pressed a second time, it shuts the service down? Is there an appropriate pattern to follow for something like this?

Thanks.


Solution

  • Use a getBroadcast() PendingIntent, where the BroadcastReceiver calls stopService().

    Or, use a getService() PendingIntent, where you send a command to your service that has the service call stopSelf().

    Or, switch the service to an IntentService, so it shuts down automatically, if that is a better service implementation for your scenario.