WP8 - 推送通知的预定任务代理

时间:2014-09-09 09:08:52

标签: windows-phone-8 push-notification scheduled-tasks pusher

我试图通过推送通知与我的应用程序进行交互,后端开发人员选择Pusher作为通知提供商。

.NET SDK非常混乱,不整洁且同步,它在WP8上不起作用,所以我重写了它,它现在工作正常。

问题是:是获取推送通知和更新磁贴/吐司所需的计划任务吗?还是有最好的方法?

我无法改变推送提供商。

1 个答案:

答案 0 :(得分:0)

您只需向手机发送Tile和Toast推送通知,即使您的应用未运行,它们也能正常运行。你不需要后台任务。

以下是我在桌面应用程序中用于将推送通知发送到Windows Phone 8.0的示例代码:

const String toastTemplate =
"<?xml version=\"1.0\" encoding=\"utf-8\"?>" +
"<wp:Notification xmlns:wp=\"WPNotification\">" +
"<wp:Toast>" +
"<wp:Text1>{0}</wp:Text1>" +
"<wp:Text2>{1}</wp:Text2>" +
"<wp:Param>{2}</wp:Param>" +
"</wp:Toast>" +
"</wp:Notification>";


String message = String.Format(toastTemplate, "Test", "updated: " + DateTime.Now.ToString(), "/Pages/SyncPage.xaml");
Status = await PushNotifiactionsManager.SendNotification(cfg.PushNotificationUri, message, 2);



public static async Task<string> SendNotification(string pushNotificationUri, string message, short notificationClass)
{
  String responseText;
  if (message.Length > 3072)
  {
    responseText = String.Format("The message must be <= 3072 bytes: {0}", message);
  }
  else
  {
    HttpClient request = new HttpClient();
    // Add message headers.
    request.DefaultRequestHeaders.Add("X-MessageID", Guid.NewGuid().ToString());
    request.DefaultRequestHeaders.Add("X-NotificationClass", notificationClass.ToString());
    if (notificationClass == 1)
    {
      request.DefaultRequestHeaders.Add("X-WindowsPhone-Target", "token");
    }
    else if (notificationClass == 2)
    {
      request.DefaultRequestHeaders.Add("X-WindowsPhone-Target", "toast");
    }
    try
    {
      // Send the message, and wait for the response.
      HttpResponseMessage response = await request.PostAsync(pushNotificationUri, new StringContent(message));
      IEnumerable<string> values;
      String connectionStatus = String.Empty;
      if (response.Headers.TryGetValues("X-DeviceConnectionStatus", out values))
      {
        connectionStatus = values.First();
      }
      String subscriptionStatus = String.Empty;
      if (response.Headers.TryGetValues("X-SubscriptionStatus", out values))
      {
        subscriptionStatus = values.First();
      }
      String notificationStatus = String.Empty;
      if (response.Headers.TryGetValues("X-NotificationStatus", out values))
      {
        notificationStatus = values.First();
      }
      responseText = String.Format("{0}: {1}, {2}, {3}, {4}",
        notificationClass == 1 ? "Tile" :
        notificationClass == 2 ? "Toast" : "Raw",
        response.StatusCode,
        connectionStatus, subscriptionStatus, notificationStatus);
    }
    catch (WebException ex)
    {
      responseText = ex.Message;
    }
  }

  return "Notification response: " + responseText;
}