GreenRobot EventBus未在Activity发布的后台服务中接收消息

时间:2014-12-16 05:03:17

标签: android

在我的活动中,我发送EventBus

@Override
protected void onResume() {
        super.onResume();
        EventBus.getDefault().post(new String("We are the champions"));
}

在我的后台服务中,我注册了EventBus并尝试从此活动发送来自此活动的消息

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

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

public void onEventBackgroundThread(String s){
        Log.d(TAG, "onEventBackgroundThread: " + s);
    }

但没有任何反应。我试图搜索互联网,但无法得到答案。

我得到的错误

No subscribers registered for event class java.lang.String
No subscribers registered for event class de.greenrobot.event.NoSubscriberEvent

1.Edit

我已经有从Service到Activity的EventBus通信。但现在我想让它反向工作(从活动到服务)。它有可能发生冲突吗?

2 个答案:

答案 0 :(得分:2)

首先,您需要定义自定义消息事件类:

public class MyMessageEvent {
   String s;
}

然后,您应该在服务中添加订阅者方法。关键是要将MyMessageEvent作为参数:

public void onEventBackgroundThread(MyMeasageEvent  myEvent){
        Log.d(TAG, "onEventBackgroundThread: " + myEvent.s);
    }

另外,请确保您的服务注册EventBus

最后,在您的活动中创建一个MyMessageEvent并将其发布在eventbus上:

MyMessageEvent myEvent = new MyMessageEvent() ;
myEvent.s = "hello" ;

EventBus.getDefault().post(myEvent) ;

如果仍然没有收到,请尝试将帖子从获取默认值拆分为单独的行。有时链接不起作用。

答案 1 :(得分:0)

我之前没有使用过greenrobot,但我认为它应该与番石榴的eventbus相似。我认为你应该创建一个事件类而不是使用String。你可以看一下https://github.com/greenrobot/EventBus。 e.g。

public class MessageEvent {
String s;
}
相关问题