如何使用 GreenRobot 的 EventBus 将事件从 Service 广播到 Activity?

How to use GreenRobot's EventBus in broadcasting events from Service to Activity?

最近我开始意识到 EventBus 库。基本上我的用例围绕服务和 Activity.

服务用于跟踪 BLE 连接的变化。

Activity 用于向 UI 报告连接状态。

我怎样才能使用库实现同样的效果..

在您的 Activity 的 onResume 方法中,注册事件:

EventBus.getDefault().register(this);

并在 onPause

注销
EventBus.getDefault().unregister(this);

当服务是运行并且它获取关于BLE的信息时,通过EventBus发送这个信息:

BLEInfo bleInfo = new BLEInfo(... // create some kind of object to aggregate the info about ble connection
EventBus.getDefault().post(bleInfo);

最后,实现 activity 获取信息的行为:

public void onEvent(BLEInfo bleInfo) {
    // update your UI based on bleInfo
}