什么是更有效的广播接收器或处理程序? [英] What is more efficient Broadcast Receiver or Handler?

查看:89
本文介绍了什么是更有效的广播接收器或处理程序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道广播接收器的onReceive()和Handler的handleMessage()在同一UI线程上运行.假设我想在同一个应用程序(进程)内的两个服务之间进行通信.我可以扩展广播接收器类并注册一个事件

I know that onReceive() of the Broadcast receiver and handleMessage() of Handler run on the same UI thread. Suppose I want to communicate between two services, within the same app (process) . I can extend a broadcast receiver class and register an event

一个处理程序,然后将其实例传递给其他服务以用于sendMessage()调用.在这两种情况下,我都需要添加一些新的开关盒.但是哪种方法更有效?让我们假设代码是线程安全的(没有UI更新).

a Handler and then pass its instance to the other service to be used for sendMessage() calls. In both the cases I would need to add some new switch case. But which approach is more efficient ? Lets assume that the code is thread safe (no UI updations).

推荐答案

我可以扩展广播接收器类并注册一个事件

I can extend a broadcast receiver class and register an event

如果您是说要通过LocalBroadcastManager进行此操作(请参阅 Kapeller先生的出色回答以获取详细信息), Handler的效率会更高一些,因为LocalBroadcastManager使用Handler.但是,性能差异不足以解决问题.其他进程内事件总线实现也是如此,例如greenrobot的EventBus和Square的Otto.所有这些都应该足够快,以至于其他问题(例如可维护性)应该是最重要的.

If you mean that you are doing this via LocalBroadcastManager (see Mr. Kapeller's excellent answer for details), Handler will be slightly more efficient, as LocalBroadcastManager uses a Handler. However, the performance difference should not be enough to matter. The same goes for other in-process event bus implementations, such as greenrobot's EventBus and Square's Otto. All should be fast enough that other concerns, such as maintainability, should be paramount.

如果您是说要通过系统广播来执行此操作(例如,在Context上调用了sendBroadcast()),则HandlerLocalBroadcastManager或其他事件总线实现将明显更快,并且更加安全也是

If you mean that you are doing this via system broadcasts (e.g., sendBroadcast() called on a Context), then Handler, LocalBroadcastManager, or other event bus implementations will be significantly faster, and more secure as well.

所有这些都假定这两个服务处于同一进程中.

All of this assumes that the two services are in the same process.

所有方法中最快的解决方案是将两种服务合并为一个.如果它们具有相同的寿命,则尤其如此.在许多情况下,在应用程序中拥有2种以上的服务是合理的,但是在没有明确理由的情况下,请勿创建大量独立的小服务.

The fastest solution of all is to combine the two services into one. This is particularly true if they have the same lifespan. There are plenty of cases where having 2+ services in an app is reasonable, but don't create lots of independent little services without a clear reason to do so.

这篇关于什么是更有效的广播接收器或处理程序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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