I'd like the following behavior: The user clicks a notification and Android stops my Service.
The problem is that stopping a Service requires a call to stopService and I cannot easily create a PendingIntent that does that.
So the only way I found to do this is to have my Service receive a special Intent extra that causes the Service to call stopSelf and stop.
Is there a simpler way to directly cancel a Service from a notification click?
You could create a simple
BroadcastReceiver
that does thestopService()
call, and use agetBroadcast()
PendingIntent
to trigger it. ThatBroadcastReceiver
could be registered in the manifest or viaregisterReceiver()
by theService
itself (in the latter case, it would dostopSelf()
rather thanstopService()
).That's probably not any simpler than what you have, though, and there is no way to directly trigger a
stopService()
call from aPendingIntent
.Thanks CommonsWare.
Here is a quick illustration of your solution for those who are interested.
Code is in the service class.