12

我想要以下行为:用户单击通知,Android 停止我的服务。

问题是停止服务需要调用 stopService 并且我不能轻易地创建一个 PendingIntent 来做到这一点。

所以我发现这样做的唯一方法是让我的服务接收一个特殊的额外意图,导致服务调用 stopSelf 并停止。

有没有更简单的方法可以从通知点击中直接取消服务?

4

2 回答 2

13

感谢CommonsWare。

以下是您的解决方案的快速说明,供感兴趣的人使用。

代码在服务类中。

// 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();
  }
};
于 2013-10-20T10:00:23.307 回答
6

您可以创建一个简单BroadcastReceiverstopService()调用,并使用 agetBroadcast() PendingIntent来触发它。这BroadcastReceiver可以在清单中或通过自身注册registerReceiver()Service在后一种情况下,它会做stopSelf()而不是stopService())。

不过,这可能并不比您拥有的更简单,而且没有办法直接stopService()PendingIntent.

于 2012-02-11T16:44:12.023 回答