androidnotificationsgoogle-cloud-messaginggcmlistenerservice

Android receives and displays double GCM push notifications


Whenever my app receives push while it's in the background, it's handled and displayed automatically.

Whenever the app is in the foreground, push is displayed manually using my GCMMessageHandler class.

Here's the snippet of GCMMessageHandler

@Override
public void onMessageReceived(String from, Bundle data) {
    super.onMessageReceived(from, data);

    MyNotification notification = new MyNotification(getApplicationContext(), data);
    notification.handleNotification();
}

The issue is that whenever my app is in the background, push notification is displayed twice instead of just once (onMessageReceived is obviously not called in this case).

I found where the issues is but I don't know how to fix it.

This is in my AndroidManifest.xml file:

    <receiver
        android:name="com.google.android.gms.gcm.GcmReceiver"
        android:exported="true"
        android:permission="com.google.android.c2dm.permission.SEND">
        <intent-filter>
            <action android:name="com.google.android.c2dm.intent.RECEIVE" />

            <category android:name="com.codepath.gcmquickstart" />
        </intent-filter>
    </receiver>

    <service
        android:name=".helpers.GCMMessageHandler"
        android:exported="false">
        <intent-filter>
            <action android:name="com.google.android.c2dm.intent.RECEIVE" />
        </intent-filter>
    </service>

I noticed that if I remove the following line:

<action android:name="com.google.android.c2dm.intent.RECEIVE" />

from either of those declarations, notifications are no longer displayed twice, but then foreground notifications don't work anymore (onMessageReceived is never called anymore).

And it's exactly the same behaviour if I remove the line from receiver or service.

Any idea how to do this properly, so that my notifications will be displayed exactly once when app is in background, with onMessageReceived still being called when in foreground?


Solution

  • Based from the Canonical IDs part of the GCM documentation, it is stated that "If a bug in the client app triggers multiple registrations for the same device, it can be hard to reconcile state and the client app might end up with duplicate messages."

    To use the Canonical ID, this SO question can help you to know how to implement it with GCM.

    For more information, check these SO question if it can help you.