12

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?

gregm
  • 12,019
  • 7
  • 56
  • 78

2 Answers2

13

Thanks CommonsWare.

Here is a quick illustration of your solution for those who are interested.

Code is in the service class.

// Create Notification 
private void initNotification() {     
  //Register a receiver to stop Service   
  registerReceiver(stopServiceReceiver, new IntentFilter("myFilter"));
  PendingIntent contentIntent = PendingIntent.getBroadcast(this, 0, new Intent("myFilter"), PendingIntent.FLAG_UPDATE_CURRENT);
  notification.setLatestEventInfo(context, contentTitle, contentText,contentIntent);  
  mNotificationManager.notify(NOTIFICATION_ID,notification);  
...
}



//We need to declare the receiver with onReceive function as below
protected BroadcastReceiver stopServiceReceiver = new BroadcastReceiver() {   
  @Override
  public void onReceive(Context context, Intent intent) {
  stopSelf();
  }
};
loonis
  • 1,317
  • 16
  • 19
6

You could create a simple BroadcastReceiver that does the stopService() call, and use a getBroadcast() PendingIntent to trigger it. That BroadcastReceiver could be registered in the manifest or via registerReceiver() by the Service itself (in the latter case, it would do stopSelf() rather than stopService()).

That's probably not any simpler than what you have, though, and there is no way to directly trigger a stopService() call from a PendingIntent.

CommonsWare
  • 986,068
  • 189
  • 2,389
  • 2,491
  • I've used this for a long time but this doesn't work anymore. Starting with Android L (5.0), you will get a DeadObjectException if the user swiped your app our of the recents list and caused Android to kill the main task and restart the service (happens if you have a local service with some UI that can be swiped out) – gnobal Jan 07 '15 at 09:22
  • 2
    @gnobal: `DeadObjectException` only occurs through binding AFAIK. This solution does not involve binding. – CommonsWare Jan 07 '15 at 12:38
  • neither does mine. I do use startService, though. But since I'm too lazy to provide a small example to show this, I'll trust that it's just my app that's not working well. In any case, I switched to a different solution you offered: http://stackoverflow.com/a/11145822/7748 :) – gnobal Jan 08 '15 at 11:19