如何使用GreenRobot的EventBus从服务到活动广播事件? [英] How to use GreenRobot's EventBus in broadcasting events from Service to Activity?

查看:230
本文介绍了如何使用GreenRobot的EventBus从服务到活动广播事件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

最近,我开始了解EventBus库.基本上,我的用例围绕着服务和活动.

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

服务用于跟踪BLE连接中的更改.

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

活动用于向UI报告该连接状态.

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

如何使用该库实现相同的目的.

How can I achieve the same using the library..

推荐答案

在活动"的onResume方法中,注册事件:

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

EventBus.getDefault().register(this);

并在onPause

EventBus.getDefault().unregister(this);

服务正在运行并且获取有关BLE的信息时,请通过EventBus发送此信息:

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
}

这篇关于如何使用GreenRobot的EventBus从服务到活动广播事件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆