cancel Service when user clicks Notification

℡╲_俬逩灬. 提交于 2019-12-12 01:40:02

问题


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?


回答1:


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

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);

The BroadcastReceiver could be an inner class in your Service to simply call stopService() in the onReceive() method.



来源:https://stackoverflow.com/questions/24448922/cancel-service-when-user-clicks-notification

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!