用 Greenrobot Eventbus 替换广播接收器以触发基于事件的功能和从服务到 activity 的数据传输是否好?

Is it good to replace broadcast receiver with Greenrobot Eventbus for triggering event based functions and data transfer from service to activity?

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

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

与LocalBroadcastManager不同,EventBus使用起来更简单。您只需完成 3 个步骤:

1- 创建一个事件 class。一个简单的 Java class 表示响应时 动作发生。

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

  EventBus.getDefault().register(this);

当然,在您的 Activity onDestroy 方法中注销它

 EventBus.getDefault().unregister(this);

3- 订阅方法是在为 EventBus 注册的相同 activity 中创建的。工作单中的示例Activity

   @Subscribe
    public void onEvent(EventClass event)

当事件发生时,你应该调用post方法,传递你之前创建的事件对象。

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

如kmaini所述,您可以将其替换为LocalBroadcastManager,但您必须自己从意图映射数据。不像 EventBus 可以传递对象。

此外,EventBus 库的创建者 greenrobot 回答了这个问题here

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

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.

EventBus 使事情变得容易得多,因为您可以在 event.You 中传递任意 Java 对象而不是对 Intents 做同样的事情,因为您的对象必须实现 Parcelable 和 "tedious" parcelable 实现,这是您可能不会在现有代码库上执行的操作。

从另一个角度来看,我认为 Android 中的广播管理器使用主线程处理程序的消息队列来处理事件。因此,如果您可以自由使用具有适当队列的不同线程(如果您没有-UI events/jobs/tasks)(例如使用另一个 HandlerThread),那么您可以利用该线程的特定队列来处理您的工作,而不会干扰 UI 事件并将您的东西与 UI 工作混合。您还可以使用线程的优先级值来平衡工作。

现在,如果 GreenRobot 在几行代码中提供了所有功能,那么我肯定会尝试它以查看任何性能提升。