在我的 MainActivity 中我使用
Intent serviceIntent = new Intent(this, myService.class);
bindService(serviceIntent,serviceConn, Context.BIND_AUTO_CREATE);
创建蓝牙连接服务,如果is.connect()
返回true,我想将变量从服务传递到单独的类,而不使用广播器。如果我创建 CheckIfConnected()
int 服务,如何从单独的类中调用它?
谢谢
最佳答案
无缝通信且无需紧密耦合应用程序代码的最简单方法是尝试使用事件
。我最喜欢的是 EventBus - android 库
。以下是您可以执行此操作的方法:
将其添加到您的 build.gradle
文件(模块级)
compile 'org.greenrobot:eventbus:3.0.0'
接下来,创建一个普通旧 Java 对象
(POJO) 来表示您的事件!
public class ServiceConnectedEvent{
private boolean isServiceConnected;
ServiceConnectedEvent(boolean isConnected){
this.isServiceConnected = isConnected;
}
public boolean isServiceConnected{
return this.isServiceConnected;
}
}
接下来,在您的服务(将充当发布者
)中,发布如下事件:
EventBus.getDefault().post(new ServiceConnectedEvent(true));
现在,在您想要通知服务连接状态的类中,您可以将其注册为订阅者
,如下所示:
EventBus.getDefault().register(this);
要在类中实际获取通知,请添加以下方法:
public void onEvent(ServiceConnectedEvent event){
if(event.isServiceConnected()){
//do what you need when service is connected
}
}
请记住,您可以传回任何您想要的内容,例如您选择的变量!
如果您位于 Activity 或 Fragment 内,则可以在 onDestroy
内取消注册
事件:
@Override
public void onDestroy(){
super.onDestroy();
EventBus.getDefault().unregister(this);
}
这应该使您的服务与任何其他类之间的通信变得容易!
我希望你能成功 - 祝你好运,编码愉快!
关于java - 服务和类之间的通信,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38529880/