EventBus : Activity does not receive event when app is in the background

Phan Dinh Thai picture Phan Dinh Thai · Mar 16, 2016 · Viewed 7.6k times · Source

I'm using EventBus to communicate between Activity and Service. Today I got a problem and don't know why.

  1. I have Activity, Fragment and Service. All of them are working fine.

  2. In Activity and Fragment I registered them to Receive events which delivered from Service

  3. In Activity and Fragment, I un-register them when onDestroy() was called.

  4. In normal cases, when Services delivers events, Fragment and Activity can receive those events and work well.

  5. But when App is pushed on the background (by presses Home or Power button), only Fragment receives events which delivered from Service, and Activity does not receive them.

  6. I did not do anything in onPause() both of Activity and Fragment.

Question:

Is there any explanation for that? And how can I make my Activity receives event like Fragment did when app is pushed on background?

Answer

Kunami picture Kunami · Jul 6, 2017

In EventBus version 3.0.0 you can use Sticky posts.

This way you can and should unregister EventBus on 'onStop()' to prevent memory leaks and still receive events when App come to foreground.

Post events this way:

EventBus.getDefault().postSticky(new MessageEvent("Hello everyone!"));

Subscribe events with sticky flag, like this:

@Subscribe(sticky = true, threadMode = ThreadMode.MAIN)
public void onEvent(MessageEvent event) {   
    textField.setText(event.message);
}

EventBus Documentation: http://greenrobot.org/eventbus/documentation/configuration/sticky-events/