用Greenrobot Eventbus代替广播接收器,以触发基于事件的功能以及从服务到活动的数据传输是否很好? [英] Is it good to replace broadcast receiver with Greenrobot Eventbus for triggering event based functions and data transfer from service to activity?

查看:223
本文介绍了用Greenrobot Eventbus代替广播接收器,以触发基于事件的功能以及从服务到活动的数据传输是否很好?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我实现了一项服务,在该服务中,我可以处理状态更改(连接,断开连接,onServiceDiscoverd,onCharacteristicChange等),并通过gatt Server从另一台设备接收数据.

I have implemented a service, where I handle the state changes(connect, disconnect, onServiceDiscoverd, onCharacteristicChange etc) and receiving data from another device through gatt Server.

我的问题是,可以使用 Greenrobot Eventbus 替换服务和活动之间的广播接收器 来有效地处理事件吗?

My question is, Can the events be handled efficiently using Greenrobot Eventbus replacing broadcast receiver between service and Activity?

推荐答案

与LocalBroadcastManager不同,EventBus使用起来更简单.您只需经过3个步骤:

Unlike LocalBroadcastManager, EventBus is more simple to use. You only go via 3 steps:

1-创建一个事件类.一个简单的Java类,代表何时响应 动作就会发生.

1- Create an event class. A simple Java class that represent the response when the action occur.

2-在您的Activity onCreate方法中将事件总线注册为订阅者

2- Register the event bus as a subscriber in your Activity onCreate method

  EventBus.getDefault().register(this);

当然,请在您的Activity onDestroy方法中取消注册

And of course, unregister it in your Activity onDestroy method

 EventBus.getDefault().unregister(this);

3-在与EventBus注册相同的活动中创建订阅方法. WorkOrderActivity中的示例

3- The subscribing method is created in the same activity that registered for the EventBus. Example in WorkOrderActivity

   @Subscribe
    public void onEvent(EventClass event)

事件发生时,您应该调用post方法,并传递之前创建的事件对象.

  EventBus.getDefault().post(new EventClass (Data));

如kmaini所述,您可以将其替换为LocalBroadcastManager,但是必须自己映射意图中的数据.与EventBus不同,EventBus可以传递对象.

As kmaini mentioned, you can replace it with LocalBroadcastManager, but you will have to map the data from the intent by yourself. Unlike EventBus which can pass objects.

EventBus库的创建者greenrobot也在此处:

Also, greenrobot, the creators of EventBus Library, answered this question here:

问:问:EventBus与Android的BroadcastReceiver/Intent有何不同? 系统吗?

Q: How's EventBus different to Android's BroadcastReceiver/Intent system?

A:与Android的BroadcastReceiver/Intent系统不同,EventBus使用 标准的Java类作为事件,并提供了更方便的API. EventBus适用于更多您不会使用的用例 想要经历设置Intent,准备Intent的麻烦 附加功能,部署广播接收器并提取Intent 临时演员.而且,EventBus的开销要低得多.

A: Unlike Android's BroadcastReceiver/Intent system, EventBus uses standard Java classes as events and offers a more convenient API. EventBus is intended for a lot more uses cases where you wouldn't want to go through the hassle of setting up Intents, preparing Intent extras, implementing broadcast receivers, and extracting Intent extras again. Also, EventBus comes with a much lower overhead.

这篇关于用Greenrobot Eventbus代替广播接收器,以触发基于事件的功能以及从服务到活动的数据传输是否很好?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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