I'm setting up an Android app built with Xamarin to receive push notifications using Google Cloud Messaging. Everything seems to be working as expected with one exception - occasionally notifications are duplicated. That is, the BroadcastReceiver responsible for handling intents from GCM receives several as opposed to one.
My first assumption was that the app was sometimes registering twice or more for notifications, but I've since confirmed that the code responsible for registration with GCM can be called only once and the issue remains. This is true with a clean install of the app on a device that has been rebooted, so I don't think it can be a case of a previous registration being left active either.
Registering for notifications:
string appVersion = context.PackageManager.GetPackageInfo(context.PackageName, 0).VersionName;
// AppSettings is a helper class I use to save important settings in shared preferences
if (AppSettings.GCMID == string.Empty || AppSettings.GCMRegisteredAppVersion != appVersion)
{
GoogleCloudMessaging gcm = GoogleCloudMessaging.GetInstance(context);
string gcmProjectNumber = context.GetString(Resource.String.GCMProjectNumber);
string gcmid = gcm.Register(gcmProjectNumber);
AppSettings.GCMID = gcmid;
AppSettings.GCMRegisteredAppVersion = appVersion;
}
// This method lets our server know that this device is ready to receive notifications
RegisterForNotifications(AppSettings.GCMID, AppSettings.GUID, PlatformType.Android);
Receiving notifications:
[BroadcastReceiver,
IntentFilter(new string[]{"com.google.android.c2dm.intent.RECEIVE"},
Categories = new string[]{ "com.example.gcm" }
)]
public class NotificationReceiver : WakefulBroadcastReceiver
{
public override void OnReceive(Context context, Intent intent)
{
var newIntent = new Intent(context, typeof(NotificationService));
newIntent.PutExtras(intent);
context.StartService(newIntent);
ResultCode = Result.Ok;
}
}
To make things even weirder, the number of duplicates seems to be related to how long the app has been running for. If I send a notification immediately after loading the app I get two push notifications, but if left for longer before sending, many more can appear. Once a notification has been received, however, the following notifications received by the app only appear once, as they should.
I'm completely at a loss as to what could be causing this; any help is appreciated, even if it's just a nod in the right direction.
Thanks.
it also possible when you send "notification" tag in your data. Just remove it from your json and messages won't be duplicates.
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