简体   繁体   English

用户单击通知时取消服务

[英]cancel Service when user clicks Notification

Similar to this post I got a service that does some work in the background. 这篇文章类似,我得到了一项在后台执行某些工作的服务。 When the service starts, I'm displaying a notification. 服务启动时,我正在显示通知。 Usually you can assing an intent to the notification that is triggered when the user clicks onto the notification. 通常,您可以为用户单击通知时触发的通知添加意图。 Mostly an activity is then started. 然后通常会开始一项活动。

But how can I use a notification to inform the background service that the user want's to cancel its operation? 但是,如何使用通知来通知后台服务用户希望取消其操作?

You can have a BroadcastReceiver to stop the Service, which is triggered through the PendingIntent of the Notification. 您可以有一个BroadcastReceiver来停止服务,该服务是通过通知的PendingIntent触发的。

Have a look at the PendingIntent.getBroadcast(...) and use it instead of the PendingIntent.getActivity() method. 看一下PendingIntent.getBroadcast(...)并使用它代替PendingIntent.getActivity()方法。 You can use it like this: 您可以像这样使用它:

  Intent broadcastIntent = new Intent(context, YourBroadcastReceiver.class);      
  PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, broadcastIntent, 0);
  Notification noti = new Notification.Builder(this)
         ...
         .setContent(pendingIntent);
         .build();

  notification.setContent(pendingIntent);

The BroadcastReceiver could be an inner class in your Service to simply call stopService() in the onReceive() method. BroadcastReceiver可以是您Service中的一个内部类,以仅在onReceive()方法中调用stopService()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM