Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Greenrobot EventBus event not received

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

The flow is something like this: Activity1 starts -> scan a barcode -> Activity2 starts -> accept or deny the response and send an event to Activity1.

So Activity2 sends 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 I have the public onEvent(MyEvent myEvent) method for receiving the event.

The problem is that the onEvent is not triggered. I looked to see maybe there's a problem on 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 seems to be the problem. If somebody could take a look and tell me what am I doing wrong I would much appreciate it.

Thanks!

like image 390
Alin Avatar asked Jan 09 '15 09:01

Alin


1 Answers

You probably need to use sticky events in this case. After Activity1 starts Activity2 it goes to 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 it

like image 85
tdavis20050 Avatar answered Nov 15 '22 06:11

tdavis20050