How to use GreenRobot's EventBus in broadcasti

2019-05-26 15:02发布

问题:

Recently I became aware of EventBus Library. Basically my use case revolves around a service and an Activity.

Service is used for tracking the changes in the BLE connection.

Activity is used for reporting that connection state to the UI.

How can I achieve the same using the library..

回答1:

In your Activity's onResume method, register for events:

EventBus.getDefault().register(this);

And unregister at onPause

EventBus.getDefault().unregister(this);

When service is running and it obtains info regarding BLE, send this info through EventBus:

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

Finally, implement the activity's behavior for getting the info:

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