Question

Is it possible to not display a push notification after the phone has actually received it?

I'm building a chatting application. Push notifications are sent every time a message is sent to user X. If user X is inside the Activity that represents the chat with user Y, and receives a message from user Y, I would like the push notification to not display.

Is this possible with regular GCM push notifications?

Was it helpful?

Solution

You can do it only with IntentService.

When a new Notification is received in your BroadcastReceiver, you will send it to the IntentService so, there before displaying Notification with NotificationBuilder have a Listener set to the Activity. If Listener exists, the user is inside the Activity, then just ignore the notifications.

For Example, define a Listener like this,

 public interface PushNotificationListenerService {
    public void showNewMessage();
}

And in your IntentService before displaying Notification,

 public void setListener(PushNotificationListenerService listener) {
    onPushReceivedCallback = listener;
 }

 Handler mHandler = new Handler(getMainLooper());
    mHandler.post(new Runnable() {
        @Override
        public void run() {
            if (onPushReceivedCallback != null) {      
              onPushReceivedCallback.showNewMessage();
              // then ignore the notification.
            }
                            else{
              // show notification
        }
    });

In you Activity,

onCreate Method,

 NotificationIntentService.getInstance(this).setListener(this);

OTHER TIPS

The messages received through GCM are processed by your IntentService which will be triggered each time a new message is received, but it's completely up to you what do you do with that message.

If you plan to act in base of an active/inactive Activity, I'd suggest declaring a global boolean that will be true when onCreate() or onResume() is called, and set to false when onDestroy() or onPause() are called. So if you receive a message, you see what value it has and act accordingly to its current state.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top