我正在配置一个使用Xamarin构建的Android应用程序,使用Google Cloud Messaging接收推送通知。除了偶尔出现重复通知的情况外,一切似乎都按预期工作。也就是说,负责处理来自GCM的意图的BroadcastReceiver会接收到多个意图而不是一个。
我的第一个假设是该应用程序有时会多次注册通知,但我已经确认负责与GCM进行注册的代码只能被调用一次,并且问题仍然存在。这在设备上进行干净安装后也是如此,因此我认为这不可能是先前的注册仍处于活动状态的情况。
我的第一个假设是该应用程序有时会多次注册通知,但我已经确认负责与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;
}
}
更加奇怪的是,重复数量似乎与应用程序运行时间有关。如果我在加载应用程序后立即发送通知,我会收到两个推送通知,但是如果等待一段时间再发送通知,则可能出现更多。但是,一旦接收到通知,应用程序接下来收到的通知只会出现一次,就像应该的那样。
我完全不知道是什么原因导致这种情况,任何帮助都将不胜感激,即使只是朝正确方向点个头。
谢谢。