Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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?

like image 688
ThaiPD Avatar asked Mar 16 '16 10:03

ThaiPD


People also ask

How does EventBus work on Android?

EventBus is an open-source library for Android and Java using the publisher/subscriber pattern for loose coupling. EventBus enables central communication to decoupled classes with just a few lines of code – simplifying the code, removing dependencies, and speeding up app development.

What is EventBus in programming?

An event bus is a design pattern (and while we'll be talking about JavaScript here, it's a design pattern in any language) that can be used to simplify communications between different components. It can also be thought of as publish/subscribe or pubsub.

How does Java event bus work?

EventBus is a software bus that allows you to register certain events and get notified when something related to that event is published. Events are in the form of classes. First, you register your class to the bus and then define methods that use the Subscribe annotation in order to register to an event.


1 Answers

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/

like image 95
Kunami Avatar answered Oct 01 '22 17:10

Kunami