Is there a straightforward way to stop a service i

2020-02-28 05:19发布

问题:

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?

回答1:

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.



回答2:

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();
  }
};