这是我们的服务和活动之间沟通的最佳方式是什么? [英] Which is the best way to communicate between service and activity?
问题描述
现在的活动可以连接到使用三种方式的服务:
Now Activity can connect to services using one of three ways:
- BroadcastReceivers
- 使者
- AIDL
- BroadcastReceivers
- Messengers
- AIDL
我觉得BroadcastReceivers是沟通的最简单的方法,但我不知道为什么,何时使用其他方法吗?或者换句话说,在这种情况下的使者或AIDL会比broadcastreceivers使用的最佳做法是什么?
I think that BroadcastReceivers is the easiest way to communicate but I'm wondering why and when to use other ways? or in other words in which cases messengers or AIDL will be the best practice to use than broadcastreceivers?
推荐答案
您可以使用的BroadcastReceiver
当你想要服务之间的通信
和活动
在应用程序。
You can use BroadcastReceiver
when you want the communication between Service
and Activity
in your application.
使者
和 AIDL
的主要用于当你的应用程序需要传达给其他进程(< A HREF =http://en.wikipedia.org/wiki/Inter-process_communication相对=nofollow> IPC )。在这种情况下,你的界面应该有一个服务
定义了处理程序
,响应不同类型的消息
的对象。
Messenger
's and AIDL
's are mainly used when your application needs to communicate to other processes(IPC). In this case your interface should have a Service
which defines a Handler
that responds to different types of Message
objects.
现在使者
和 AIDL
之间的区别是pretty的简单。当您使用使者
后,它会将所有的请求到一个单独的线程。所以,你的服务
不必是线程安全的。如果,你希望你的服务
来,那么你可以使用 AIDL
直接同时处理多个请求。在这种情况下,你的服务
必须能够多线程和建立线程安全的。事实上使者
是在顶部 AIDL
实施。
Now the difference between Messenger
and AIDL
is pretty simple. When you use Messenger
, it queues all requests into a single thread. So your Service
doesn't have to be thread safe. If, you want your Service
to handle multiple requests simultaneously, then you can use AIDL
directly. In this case, your Service
must be capable of multi-threading and be built thread-safe. In fact Messenger
is implemented on the top of AIDL
.
为了更好地理解一下绑定服务
您也应该检查从答案<一href="http://stackoverflow.com/questions/7372676/broadcastreceiver-or-messenger-via-handler">BroadcastReceiver或者通过处理器通
这篇关于这是我们的服务和活动之间沟通的最佳方式是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!