Search code examples
androidbluetooth-lowenergygreenrobot-eventbus

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


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..


Solution

  • 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
    }