本文介绍了取消服务,当用户点击通知的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

类似this帖子我得到了确实在后台的一些工作的服务。在服务启动时,我展示的通知。通常你可以assing的意图,当用户点击到的通知所触发的通知。大多是一个活动,然后启动。

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?

推荐答案

您可以有一个BroadcastReceiver停止服务,这是通过通知的触发的PendingIntent

You can have a BroadcastReceiver to stop the Service, which is triggered through the PendingIntent of the Notification.

有一个看的,并用它代替 PendingIntent.getActivity()的方法。您可以使用它是这样的:

Have a look at the PendingIntent.getBroadcast(...) and use it instead of the PendingIntent.getActivity() method. 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);

该广播接收器可能是一个内部类中为您服务,只需拨打 stopService()的onReceive()方法。

这篇关于取消服务,当用户点击通知的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-30 23:37