我正在設置一個使用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;
}
}
要米甚至更奇怪的事情,重複的數量似乎與應用程序運行了多長時間有關。如果我在加載應用程序後立即發送通知,我會得到兩個推送通知,但如果在發送之前保留更長時間,則可能會出現更多更多通知。但是,收到通知後,應用程序收到的以下通知只會顯示一次,因爲它們應該這樣做。
我茫然,什麼可能會導致這完全是;任何幫助都是值得讚賞的,即使它只是在正確的方向點頭。
謝謝。
您如何確定您多次收到通知?您的廣播接收機是否使用相同的通知或不同的通知多次觸發? –
我故意從服務器發送一個通知,並且廣播接收器會多次觸發該通知。意圖是重複的。 –