为什么GCM推送通知会重复?

时间:2015-08-25 21:49:21

标签: android xamarin push-notification google-cloud-messaging

我正在设置一个使用Xamarin构建的Android应用,以使用Google Cloud Messaging接收推送通知。一切似乎都按预期工作,但有一个例外 - 偶尔会有重复的通知。也就是说,负责处理来自GCM的意图的BroadcastReceiver接收几个而不是一个。

我的第一个假设是应用程序有时会注册两次或更多次通知,但我已经确认负责注册GCM的代码只能调用一次,问题仍然存在。在已重新启动的设备上干净地安装应用程序时,情况确实如此,因此我认为不会出现先前注册处于活动状态的情况。

注册通知:

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);

接收通知:

[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;
  }
}

为了让事情变得更奇怪,重复数量似乎与应用程序的运行时间有关。如果我在加载应用程序后立即发送通知,我会收到两个推送通知,但如果在发送之前保留更长时间,则会出现更多通知。但是,一旦收到通知,应用程序收到的以下通知只会出现一次。

我完全不知道造成这种情况的原因;任何帮助都会受到赞赏,即使只是朝着正确的方向点头。

感谢。

3 个答案:

答案 0 :(得分:1)

当您发送"通知"标记在您的数据中。只需从你的json中删除它,消息就不会重复。

答案 1 :(得分:0)

" ...如果在发送之前保留更长时间,可以出现更多。收到后...应用程序收到的通知只会出现一次" - >在所有测试中这是否一致?

请检查两件事:发送通知的服务器端代码和GCM message status的Play Dev控制台。在前者中,您可能会两次发送相同的消息。在后者中,查找您使用的注册令牌,并查看服务器是否有重复的发送。

答案 2 :(得分:0)

我更新到最新版本的GooglePlayServices.GCM库,并且重复的意图停止显示。这可能意味着它是图书馆的一个错误,但不幸的是我从来没有找到问题的确切来源,因此无法确认。