2015-09-04 45 views
0

爲了在pushsharp中發送批量通知,我使用了foreach循環。 我正在爲同一通知收到多個回叫。一個通知的多個回調Pushsharp

假設我發送通知給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); 
     } 

回答

0

在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 
}