我想要以下行为:用户单击通知,Android 停止我的服务。
问题是停止服务需要调用 stopService 并且我不能轻易地创建一个 PendingIntent 来做到这一点。
所以我发现这样做的唯一方法是让我的服务接收一个特殊的额外意图,导致服务调用 stopSelf 并停止。
有没有更简单的方法可以从通知点击中直接取消服务?
我想要以下行为:用户单击通知,Android 停止我的服务。
问题是停止服务需要调用 stopService 并且我不能轻易地创建一个 PendingIntent 来做到这一点。
所以我发现这样做的唯一方法是让我的服务接收一个特殊的额外意图,导致服务调用 stopSelf 并停止。
有没有更简单的方法可以从通知点击中直接取消服务?
感谢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(); } };
您可以创建一个简单BroadcastReceiver
的stopService()
调用,并使用 agetBroadcast()
PendingIntent
来触发它。这BroadcastReceiver
可以在清单中或通过自身注册registerReceiver()
(Service
在后一种情况下,它会做stopSelf()
而不是stopService()
)。
不过,这可能并不比您拥有的更简单,而且没有办法直接stopService()
从PendingIntent
.