I'm using EventBus
to communicate between Activity
and Service
. Today I got a problem and don't know why.
I have Activity
, Fragment
and Service
. All of them are working fine.
In Activity
and Fragment
I registered
them to Receive
events
which delivered from Service
In Activity
and Fragment
, I un-register
them when onDestroy()
was called.
In normal cases, when Services
delivers events
, Fragment
and Activity
can receive those events
and work well.
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.
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?
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.
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.
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.
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/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With