gpt4 book ai didi

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

转载 作者:IT老高 更新时间:2023-10-28 23:23:29 32 4
gpt4 key购买 nike

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

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

最佳答案

与 LocalBroadcastManager 不同,EventBus 更易于使用。您只需执行 3 个步骤:

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

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

  EventBus.getDefault().register(this);

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

 EventBus.getDefault().unregister(this);

3- 订阅方法是在为 EventBus 注册的同一 Activity 中创建的。 WorkOrderActivity 中的示例

   @Subscribe
public void onEvent(EventClass event)

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

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

正如 kmaini 所提到的,您可以将其替换为 LocalBroadcastManager,但您必须自己映射来自 Intent 的数据。与可以传递对象的 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.

关于android - 用 Greenrobot Eventbus 替换广播接收器是否可以触发基于事件的功能和从服务到 Activity 的数据传输?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33141091/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com