EventBus event not received from Greenrobot

I am using Greenrobot EventBus to pass events from one activity to another.

The flow looks something like this: Start Activity1 -> barcode scan -> Activity2 start -> accept or reject response and send an event to Activity1.

So Activity2 dispatches a new event to Activity1 by doing something like:

@Override
public void onCreate(){
  EventBus.getDefault().register(this);
  // other initialization code
  EventBus.getDefault().post(new MyEvent());
}

      

In Activity1, I register the event bus and also get a public onEvent (MyEvent myEvent) method to receive the event.

The problem is the onEvent is not firing. I looked, maybe there is a problem with the event bus object (like different instances or someting in Activity 1 and 2), but it's the same instance.

I don't know what the problem is. If someone can take a look and tell me what I am doing wrong, I would really appreciate it.

Thank!

+3


source to share


3 answers


You will probably have to use sticky events in this case. After Activity1 starts Activity2, it goes into the background and can no longer receive any events.

Put this in your Activity1 instead of EventBus.getDefault (). register (Object Event)

@Override
public void onStart() {
    super.onStart();
    EventBus.getDefault().registerSticky(this);
}

      

and replace



EventBus.getDefault().post(new MyEvent());

      

in Activity2 with

EventBus.getDefault().postSticky(new MyEvent());

      

Here is a link to the documentation explaining this

+3


source


What does your unregistered Activity1 account look like?

I had the same problem due to doing this:

Activity1.java

@Override
protected void onStop() {
     super.onStop()
     EventBus.getDefault().unregister(this);
}

      



The problem is when Activity2 onStop

gets called when it starts , so removing the event subscription. I was able to solve this by moving unregister to onDestroy like so:

Activity1.java

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

      

+2


source


class test

public class TestEventBus {

private String label;

public String getLabel() {
    return label;
}

public void setLabel(String label) {
    this.label = label;
}
}

      

Activity A

TestEventBus t = new TestEventBus();
t.setLabel("oi");
EventBus.getDefault().post( t );

      

Activity B

@Subscribe(sticky = true, threadMode = ThreadMode.MAIN)
public void onMessageEvent(TestEventBus test) {

Toast.makeText(this, "label "+test.getLabel(), 
Toast.LENGTH_SHORT).show();

};

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

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

 }

      

0


source







All Articles