【发布时间】:2015-08-25 21:49:21
【问题描述】:
我正在设置一个使用 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;
}
}
更奇怪的是,重复的数量似乎与应用程序运行的时间有关。如果我在加载应用程序后立即发送通知,我会收到两个推送通知,但如果在发送前等待更长时间,可能会出现更多通知。但是,一旦收到通知,应用程序收到的以下通知只会出现一次,因为它们应该出现。
我完全不知道是什么原因造成的;任何帮助都表示感谢,即使这只是对正确方向的点头。
谢谢。
【问题讨论】:
-
你如何确定你收到了多次通知?您的广播接收器是使用相同的通知还是不同的通知多次触发?
-
我故意从服务器发送一个通知,并且广播接收器被该通知触发多次。意图是重复的。
标签: android xamarin push-notification google-cloud-messaging