是否有直接的方法来停止服务以响应用户单击通知? [英] Is there a straightforward way to stop a service in response to a user clicking a notification?

查看:68
本文介绍了是否有直接的方法来停止服务以响应用户单击通知?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想要以下行为: 用户单击通知,Android停止我的服务.

I'd like the following behavior: The user clicks a notification and Android stops my Service.

问题在于,停止服务需要调用stopService,而我无法轻松创建执行该操作的PendingIntent.

The problem is that stopping a Service requires a call to stopService and I cannot easily create a PendingIntent that does that.

因此,我发现这样做的唯一方法是让我的服务收到一个特殊的Intent附加信息,该附加Intent会导致该服务调用stopSelf并停止.

So the only way I found to do this is to have my Service receive a special Intent extra that causes the Service to call stopSelf and stop.

有没有更简单的方法可以从通知点击中直接取消服务?

Is there a simpler way to directly cancel a Service from a notification click?

推荐答案

您可以创建一个简单的BroadcastReceiver来执行stopService()调用,并使用getBroadcast() PendingIntent来触发它. 可以通过Service本身在清单中或通过registerReceiver()注册BroadcastReceiver(在后一种情况下,它将执行stopSelf()而不是stopService()).

You could create a simple BroadcastReceiver that does the stopService() call, and use a getBroadcast() PendingIntent to trigger it. That BroadcastReceiver could be registered in the manifest or via registerReceiver() by the Service itself (in the latter case, it would do stopSelf() rather than stopService()).

但是,这可能比您所拥有的要简单得多,并且没有办法直接从PendingIntent触发stopService()调用.

That's probably not any simpler than what you have, though, and there is no way to directly trigger a stopService() call from a PendingIntent.

这篇关于是否有直接的方法来停止服务以响应用户单击通知?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆