通过处理程序的广播接收器或信使
我有一个 IntentService
,它需要将消息传递给 Activity
。 我知道有两种方法可以做到这一点。
在
Service
端使用sendBroadcast()
,同时在Activity
端注册一个broadcastReciever
来接收消息。将
Messenger
传递到Service端
,它将指向Activity
端的Handler
,它将准备好从服务接收该消息。
哪一个适合什么目的?或者两者都做同样的事情?
I have an IntentService
which need to pass a message to an Activity
.
I know two ways of doing so.
use
sendBroadcast()
at theService
side while registering abroadcastReciever
at theActivity
side which will receiver the message.passing a
Messenger
to the Serviceside
, which will point to aHandler
at theActivity
side, which will be ready to receive that message from the service.
Which one is good for which purpose? Or both of them do the same?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果您的 IntentService 不知道该 Activity 是否存在(例如,可能已被销毁),或者是否有多个 Activity 可能位于前台并且想要了解正在发生的情况,我会使用
sendOrderedBroadcast()
。如果需要,您还可以安排一个“后备”BroadcastReceiver
,它可以在需要时发出通知,正如我在 此博文 并在 此示例项目。不过,您的任何一种技术都可以发挥作用。
If your
IntentService
does not know whether the activity will exist (e.g., might have been destroyed), or if there are multiple activities that might be in the foreground and would want to know about what's going on, I'd usesendOrderedBroadcast()
. You can arrange to then also have a "backstop"BroadcastReceiver
that could raise a Notification, if desired, as I outline in this blog post and demonstrate in this sample project.Either of your techniques can work, though.