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..
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
}
来源:https://stackoverflow.com/questions/33147029/how-to-use-greenrobots-eventbus-in-broadcasting-events-from-service-to-activity