我想要以下行为: 用户点击通知,Android 停止我的服务。
问题是停止服务需要调用 stopService,而我无法轻松地创建执行此操作的 PendingIntent。
所以我发现这样做的唯一方法是让我的服务接收一个特殊的 Intent extra,它会导致服务调用 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(); } };
关于android - 是否有一种直接的方法来响应用户单击通知来停止服务?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9241682/