2015-11-05 128 views
0

我正在使用google的GCM API開發wcf推送通知服務。我創建了一項服務,發送到使用我的應用程序的所有設備,但是,我想要針對某個設備。我想我必須使用我註冊GCM服務時獲得的令牌。但我不知道在哪裏以及如何暗示它。大多數在線帖子都是在PHP中,當我看到代碼時,我有點困惑。任何一個使用C#implmentation建議或一般可能是? 這裏是我的代碼爲所有設備:提前使用gcm的android推送通知

public bool notify(string sender, string message) 
    { 
     var jGcmData = new JObject(); 
     var jData = new JObject(); 
     bool Value; 

     jData.Add("message", message); 
     jData.Add("name", sender); 
     jGcmData.Add("to", "/topics/global"); 
     jGcmData.Add("data", jData); 

     var url = new Uri("https://gcm-http.googleapis.com/gcm/send"); 
     try 
     { 
      using (var client = new HttpClient()) 
      { 
       client.DefaultRequestHeaders.Accept.Add(
        new MediaTypeWithQualityHeaderValue("application/json")); 

       client.DefaultRequestHeaders.TryAddWithoutValidation(
        "Authorization", "key=" + API_KEY); 

       Task.WaitAll(client.PostAsync(url, 
        new StringContent(jGcmData.ToString(), Encoding.Default, "application/json")) 
       .ContinueWith(response => 
       { 
        Console.WriteLine(response); 
        Console.WriteLine("Message sent: check the client device notification tray."); 
       })); 
      } 
      Value = true; 
     } 
     catch (Exception e) 
     { 
      Console.WriteLine("Unable to send GCM message:"); 
      Console.Error.WriteLine(e.StackTrace); 
      Value = false; 
     } 
     return Value; 
    } 

的感謝!

回答

0

首先,我認爲你不應該重新發明輪子,並且包含一個Push消息庫來完成所有冗餘工作。

I use PushSharp

然後一切都是蛋糕。

聲明以下處理程序類 使用SendGCMNotification方法只是拋出一個對象來序列化和特定用戶的推送消息傳遞id。

public class PushNotificationHandler : IDisposable 
{ 
    private static readonly string googleApiKey; 
    private static PushBroker pushBrokerInstance; 
    static PushNotificationHandler() 
    { 
     googleApiKey = ConfigurationManager.AppSettings["GoogleAPIKey"].ToString(); 
     pushBrokerInstance = new PushBroker(); 
     pushBrokerInstance.RegisterGcmService(new GcmPushChannelSettings(googleApiKey)); 

    } 
    public static void SendGCMNotification(Notification messageObj, String CloudMessagingId) 
    { 
     String Content = Newtonsoft.Json.JsonConvert.SerializeObject(messageObj); 
     pushBrokerInstance.QueueNotification(new GcmNotification().ForDeviceRegistrationId(CloudMessagingId).WithJson(Content)); 
    } 
} 
+0

我看到很多帖子使用pushSharp,我會看看它。謝謝! – user3406302