GreenRobot EventBus does not receive a message in the background sent by activity

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 an EventBus and try to get a sent message from an Activity, such as

 @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 the Internet, but could not get an answer.

The 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 an EventBus connection from service to activity. But now I want it to work the other way too (from Activity to Service). Is it possible that this conflicts?

+6
source share
2 answers

First you need to define a custom message event class:

 public class MyMessageEvent { String s; } 

Then you must add the subscriber method to your service. The key point is to include your MyMessageEvent as a parameter:

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

Also, make sure your service is registered using EventBus .

Finally, create a MyMessageEvent in your activity and host it in the eventbus:

 MyMessageEvent myEvent = new MyMessageEvent() ; myEvent.s = "hello" ; EventBus.getDefault().post(myEvent) ; 

If it is still not received, try splitting the message into a separate line by default. Sometimes the chain doesn't work.

+2
source

I have not used greenrobot before, but I think it should look like guava eventbus. I think you should create an event class instead of using String. You can look at https://github.com/greenrobot/EventBus . eg.

 public class MessageEvent { String s; } 
0
source

Source: https://habr.com/ru/post/979676/


All Articles