BroadcastReceiver的或Messenger通过处理程序 [英] BroadcastReceiver or Messenger via Handler
问题描述
我有一个 IntentService
这需要传递一个消息给活动
。
我知道这样做的两种方式。
I have an IntentService
which need to pass a message to an Activity
.
I know two ways of doing so.
-
使用
sendBroadcast()
在服务
一边登记broadcastReciever
在活动
侧,将接收的消息。
use
sendBroadcast()
at theService
side while registering abroadcastReciever
at theActivity
side which will receiver the message.
传递使者
到服务侧
,它会指向一个处理程序
在活动
端,这将是准备接收消息的服务。
passing a Messenger
to the Service side
, which will point to a Handler
at the Activity
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?
推荐答案
如果你的 IntentService
不知道活动是否会存在(例如,可能已被破坏),或者是否有可能是在前台,并会想知道发生了什么事情,我会使用多种活动 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 use sendOrderedBroadcast()
. 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.
这篇关于BroadcastReceiver的或Messenger通过处理程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!