我正在构建一个应用程序来收集从蓝牙le接收到的感官数据。此外,我需要收集从安装的GPS传感器智能手机位置。为了达到这个目的,我做了三个服务:
目前,我正在使用广播接收器在服务之间发送数据,但我知道这是一个糟糕的解决方案。实现服务间通信的最佳实践是什么?
发布于 2019-09-01 11:42:36
您可以简单地使用EventBus库:
//1. Define a java class that represents your event:
public static class MessageEvent {
/* Additional fields if needed */
}
//2.Post events at your origin like as below and receive them in destination (@Subscribe methods):
EventBus.getDefault().post(new MessageEvent());
//3.Prepare subscribers in destinations: Declare and annotate your subscribing method, optionally specify a thread mode:
@Subscribe(threadMode = ThreadMode.MAIN)
public void onMessageEvent(MessageEvent event) {
/* Do something */
};
//4.Register and unregister your subscriber in the destination, according to your component (here service class) life cycle:
@Override
public void onCreate() {
super.onCreate();
EventBus.getDefault().register(this);
}
@Override
public void onDestroy() {
EventBus.getDefault().unregister(this);
super.onDestroy();
}希望这能帮到你。
https://stackoverflow.com/questions/56930811
复制相似问题