GreenRobot EventBus错误:没有订阅者注册活动

时间:2016-05-27 09:56:17

标签: android service greenrobot-eventbus

我正在尝试使用GreenRobot EventBus将活动从活动发布到服务。 但是当我尝试发布事件时,logcat显示以下消息:

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

以下是我在活动中用来发布活动的代码:

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");
  }
}

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

4 个答案:

答案 0 :(得分:1)

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

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

答案 1 :(得分:1)

由于@jdsjlzx的回答
我用另一种方式做到了

if (EventBus.getDefault().hasSubscriberForEvent(CharSequence.class)) {
    EventBus.getDefault().post(someCharSequenceVar);
}

因此,如果没有订户注册

,就不要发送事件

答案 2 :(得分:0)

当您的活动发布活动时,请检查您的服务是否实际正在运行。

此外,不是试图将事件发布到服务中,而是为什么不以意图启动它?

答案 3 :(得分:0)

您只需注册一次订户。因此,在onCreate上进行注册,如下所示:

@Override
protected void onStart() {
  super.onStart();
  EventBus.getDefault().register(this);
}

相反,您需要将取消注册移动到名为以下内​​容的super.onDestroy()之前:

@Override
protected void onDestroy() {
    EventBus.getDefault().unregister(this);
    super.onDestroy();
}
相关问题