Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 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?

like image 471
gregm Avatar asked Feb 11 '12 16:02

gregm


2 Answers

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();
  }
};
like image 118
loonis Avatar answered Oct 21 '22 14:10

loonis


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.

like image 6
CommonsWare Avatar answered Oct 21 '22 15:10

CommonsWare