Skip to content Skip to sidebar Skip to footer

Is There A Straightforward Way To Stop A Service In Response To A User Clicking A Notification?

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 eas

Solution 1:

Thanks CommonsWare.

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

Code is in the service class.

// Create Notification privatevoidinitNotification() {     
  //Register a receiver to stop Service   
  registerReceiver(stopServiceReceiver, newIntentFilter("myFilter"));
  PendingIntentcontentIntent= PendingIntent.getBroadcast(this, 0, newIntent("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 belowprotectedBroadcastReceiverstopServiceReceiver=newBroadcastReceiver() {   
  @OverridepublicvoidonReceive(Context context, Intent intent) {
  stopSelf();
  }
};

Solution 2:

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.

Post a Comment for "Is There A Straightforward Way To Stop A Service In Response To A User Clicking A Notification?"