Skip to content Skip to sidebar Skip to footer

Cancel Service When User Clicks Notification

Similar to this post I got a service that does some work in the background. When the service starts, I'm displaying a notification. Usually you can assing an intent to the notifica

Solution 1:

You can have a BroadcastReceiver to stop the Service, which is triggered through the PendingIntent of the Notification.

Have a look at the PendingIntent.getBroadcast(...) and use it instead of the PendingIntent.getActivity() method. You can use it like this:

IntentbroadcastIntent=newIntent(context, YourBroadcastReceiver.class);      
  PendingIntentpendingIntent= PendingIntent.getBroadcast(context, 0, broadcastIntent, 0);
  Notificationnoti=newNotification.Builder(this)
         ...
         .setContent(pendingIntent);
         .build();

  notification.setContent(pendingIntent);

The BroadcastReceiver could be an inner class in your Service to simply call stopService() in the onReceive() method.

Post a Comment for "Cancel Service When User Clicks Notification"