Search code examples
androidpubnub

PubNub - Messages are received both as Push and as realtime [Android]


I subscribe to all necessary channels in 2 places:

// For receiving real time (regular) messages
pubnub.subscribe().channels(channels).execute();

and for Push

pubnub.addPushNotificationsOnChannels()
                            .pushType(PNPushType.FCM)
                            .channels(channels)
                            .deviceId(firebaseMessageingTokenForThisUser)

When I send messages I specify data for Push as well:

PushPayloadHelper pushPayloadHelper = new PushPayloadHelper();

// set FCM payload
pushPayloadHelper.setFcmPayload(fcmPayload);

// Set APNs payload
pushPayloadHelper.setApnsPayload(apnsPayload);

// Common payload for realtime PubNub subscribe
Map<String, Object> commonPayload = new HashMap<>();
commonPayload.put("message", jsonPayload);
pushPayloadHelper.setCommonPayload(commonPayload);

pubnub.publish()
                .channel(channelName)
                .message(pushPayloadHelper.build())...

Expected behaviour:

  1. When Android client is in foreground messages are delivered as real time
  2. When app was closed/killed messages are delivered as Push

Current behavior:

When app is running, messages are delivered both as Push (Firebase Push service method is invoked)
and real time (public void message(@NotNull PubNub pubnub, @NotNull PNMessageResult message) method is invoked)

What do I do wrong? Couldn't find anything about it in the official documentation.


Solution

  • PubNub Realtime Messaging & Mobile Push Notifications

    subscribe to all necessary channels in 2 places

    First, just to keep terminology in order, you subscribe to channels for realtime messages and you register devices on channels for mobile push notifications. Subscribe only applies to realtime messages. It's a nitpick but important to keep things clear when we talk about this.

    And yes, every time you publish a message that includes a mobile push payload, it gets delivered to active subscribers to the channel and delivered as a mobile push notification to devices that are registered for push on that channel. This is expected and necessary.

    The trick is that when the app is in the foreground (active), you simply just don't display the push notification, because you received it in the addListener''s message` handler.

    So the question is, what does your "mobile push message receiver" handler look like?

    Here's a really old blog/video that explains all this. While it is over 5 years old, it is still relevant.