多个回调为一个通知Pushsharp

本文关键字:一个 通知 Pushsharp 回调 | 更新日期: 2023-09-27 18:11:04

对于在pushsharp中发送批量通知,我使用foreach循环。我收到多个电话回同一个通知。

假设我向3个设备发送通知,我得到10次回调。它为所有3个设备重复回调通知。

foreach (var recipient in recipients)
        {
            //Wire up the events for all the services that the broker registers
            push.OnChannelCreated += push_OnChannelCreated;
            push.OnChannelDestroyed += push_OnChannelDestroyed;
            push.OnChannelException += push_OnChannelException;
            push.OnDeviceSubscriptionChanged += push_OnDeviceSubscriptionChanged;
            push.OnDeviceSubscriptionExpired += push_OnDeviceSubscriptionExpired;
            push.OnNotificationFailed += push_OnNotificationFailed;
            push.OnNotificationRequeue += push_OnNotificationRequeue;
            push.OnNotificationSent += push_OnNotificationSent;
            push.OnServiceException += push_OnServiceException;
            var gcmMessage = new GCMMessage 
                                 {
                                     message = TemplateUtility.GetNotificationBodyGcm(TemplateName, recipient),
                                     badge=7,
                                     sound="sound.caf"              
                                 };
            string jsonGcmMessage = Newtonsoft.Json.JsonConvert.SerializeObject(gcmMessage);
            push.RegisterGcmService(new GcmPushChannelSettings(ConfigurationManager.AppSettings["GCM_Development_ServerKey"].ToString()));
            //push.RegisterGcmService(new GcmPushChannelSettings(ConfigurationManager.AppSettings["GCM_Production_ServerKey"].ToString()));                
            push.QueueNotification(new GcmNotification().ForDeviceRegistrationId(recipient.DeviceRegistrationToken)
                                  //.WithJson("{'"message'":'"Hi PushNoti'",'"badge'":7,'"sound'":'"sound.caf'"}"));
                                  .WithJson(jsonGcmMessage));

            //Stop and wait for the queues to drains before it dispose 
            push.StopAllServices(waitForQueuesToFinish: true);
        }

多个回调为一个通知Pushsharp

在c#中,将同一个回调多次添加到委托中会导致该回调被调用的次数与添加的次数一样多。你可能想要的是将代码中不依赖于recipient的部分移出循环。这样,无论recipients的计数如何,每个回调方法只注册一次。

push.OnChannelCreated += push_OnChannelCreated;
push.OnChannelDestroyed += push_OnChannelDestroyed;
push.OnChannelException += push_OnChannelException;
push.OnDeviceSubscriptionChanged += push_OnDeviceSubscriptionChanged;
push.OnDeviceSubscriptionExpired += push_OnDeviceSubscriptionExpired;
push.OnNotificationFailed += push_OnNotificationFailed;
push.OnNotificationRequeue += push_OnNotificationRequeue;
push.OnNotificationSent += push_OnNotificationSent;
push.OnServiceException += push_OnServiceException;
// not sure about this one
push.RegisterGcmService(new GcmPushChannelSettings(ConfigurationManager.AppSettings["GCM_Development_ServerKey"].ToString()));
foreach(var recipient in recipients)
{
    // do other things here
}
相关文章: