I use firebase to send notification. When the app is in foreground, the notification is received by the class that extends FirebaseMessagingService
. So in onMessageReceived
, I do this:
EventBus.getDefault().postSticky(new NotificationEvent(body, title, url));
I have two activities that listeners for this event. Activity A and Activity B.
In both activities, I do this:
@Subscribe(sticky = true, threadMode = ThreadMode.MAIN)
public void consumeNotification(NotificationEvent event) {
//Consume event
}
@Override
public void onStart() {
super.onStart();
EventBus.getDefault().register(this);
Log.d(TAG, "onStart called");
}
@Override
public void onStop() {
NotificationEvent event = EventBus.getDefault().getStickyEvent(NotificationEvent.class);
if (event != null) {
EventBus.getDefault().removeStickyEvent(event);
}
EventBus.getDefault().unregister(this);
super.onStop();
Log.d(TAG, "onStop called");
}
Now, there is a button in Activity A that launches Activity B.
If activity A is visible on the screen, and I receive the notification (which triggers the event), the event is consumed that first time.
So when I click the button to launch Activity B (onStop
is called on Activity A), but surprisingly the event is received again in Activity B when it was supposed to have removed when onStop
was called in Activity A.
Also, if Activity B is visible on the screen and I receive the notification (which triggers the event), the event is also consumed that first time.
But when I clicked the physical back button to go back to Activity A, the event is received again in Activity A when it's supposed to have been removed.
Please, what's supposed to be the cause of this and how can it be fixed?
NOTE: I chose to use stick event because If I use non-sticky event, the event is not delivered when the screen has deemed off on either of the activities.
Look like you needed to call EventBus.getDefault().removeStickyEvent(event);
inside consumeNotification(NotificationEvent event)
and leave EventBus.getDefault().unregister(this);
in onStop()
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