java - 服务和类之间的通信

标签 java android service

在我的 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/

相关文章:

java - log4j2 logger.entry() 方法不打印日志消息

android - RESTful Android ContentProvider URI

Android:应用程序未运行时接收推送通知

java - 滚动时 ListView 项目未锁定

java - 我在 Release模式下运行 Flutter 应用程序时遇到问题 - android

android - 来自 FragmentActivity 的 fragment 在一些设备上不显示背景图像

安卓错误日期

c - 执行从 Windows 服务捕获屏幕截图的程序

android - 如何在 Android 中更新服务中的 Bundle 数据?

java - 使用 switch 语句处理 fragment 中的 onBackPressed()