Reputation: 6369
In my Activity I send EventBus
@Override
protected void onResume() {
super.onResume();
EventBus.getDefault().post(new String("We are the champions"));
}
In my background service I register EventBus and try to get sent message from Activity like this
@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);
}
But nothing happens. I tried to search internet but couldn't get answer.
Errors I get
No subscribers registered for event class java.lang.String
No subscribers registered for event class de.greenrobot.event.NoSubscriberEvent
1.Edit
I already have EventBus communication from Service to Activity. But now I want to have it also to work in reverse direction(From Activity to Service). So is it possible that it conflicts?
Upvotes: 6
Views: 3364
Reputation: 3038
First you need to define a custom message event class:
public class MyMessageEvent {
String s;
}
Then you should add a subscriber method into your service. Key thing is to include your MyMessageEvent
as the parameter:
public void onEventBackgroundThread(MyMeasageEvent myEvent){
Log.d(TAG, "onEventBackgroundThread: " + myEvent.s);
}
Plus make sure your service registers with EventBus
.
Finally, create a MyMessageEvent
in your activity and post it on the eventbus:
MyMessageEvent myEvent = new MyMessageEvent() ;
myEvent.s = "hello" ;
EventBus.getDefault().post(myEvent) ;
If it still doesn't get received, try splitting the post onto a seperate line from the get default. Sometimes chaining doesn't work.
Upvotes: 2
Reputation: 720
I have not used greenrobot before but I think it should be similar to guava's eventbus. I think you should create an event class instead of using String. You can have a look at https://github.com/greenrobot/EventBus. e.g.
public class MessageEvent {
String s;
}
Upvotes: 0