android - GreenRobot EventBus 错误 : No subscribers registered for event

标签 android service greenrobot-eventbus

我正在尝试使用 GreenRobot EventBus 将事件从 Activity 发布到 Service . 但是当我尝试发布事件时,logcat 显示以下消息:

No subscribers registered for event class com.example.dhaval.homeexamples.CallBackEvent
No subscribers registered for event class org.greenrobot.eventbus.NoSubscriberEvent

这是我在 Activity 中用于发布事件的代码:

EventBus.getDefault().post(new CallBackEvent(1));

以下是我的CallBackEvent:

public class CallBackEvent {
  private int a;
  public CallBackEvent(int a) {
    this.a = a;
  }
}

以下是我的具有订阅者的服务类:

public class BackService extends Service{

  @Nullable
  @Override
  public IBinder onBind(Intent intent) {
    return null;
  }

  @Override
  public void onCreate() {
    super.onCreate();
    EventBus.getDefault().register(this);
  }

  @Override
  public int onStartCommand(Intent intent, int flags, int startId) {
    return super.onStartCommand(intent, flags, startId);
  }

  @Override
  public void onDestroy() {
    super.onDestroy();
    EventBus.getDefault().unregister(this);
  }

  @Subscribe
  public void onEvent(CallBackEvent callBackEvent){
    Log.d("service", "CallBackEvent : called");
  }
}

为什么会这样?因为当我将事件从服务发布到 Activity 时它工作正常。但是,当我尝试使用此代码(从服务到 Activity )时,它不起作用。

最佳答案

问题我解决了,代码如下:

if(!EventBus.getDefault().hasSubscriberForEvent(CallBackEvent.class)) {
        EventBus.getDefault().register(this);
}

关于android - GreenRobot EventBus 错误 : No subscribers registered for event,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37480413/

相关文章:

android - 集成 tabhost 和抽屉导航

java - EventBus 粘性事件是否在订阅者方法上自动删除?

android - Android 上的 EventBus : how to implement dynamic queues vs. 基于类的事件订阅?

android - DialogFragment 中的 ViewPager 不会更改单击时的选项卡

android - 适用于 Android 的嵌入式 HTTP 服务器

android - 屏幕支持大屏幕吗?

windows - PID在netstat中存在,但在任务管理器中不存在

sql-server - 启动 AX 2012 R3 服务时出错

unit-testing - Grails Spock 单元测试需要模拟事务管理器

android - 在 ViewPager 中使用 EventBus 时获取混合数据