Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

GreenRobot EventBus not receiving message in Background service posted by Activity

Tags:

android

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?

like image 973
Rafael Avatar asked Dec 16 '14 05:12

Rafael


1 Answers

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.

like image 149
DEzra Avatar answered Oct 28 '22 20:10

DEzra