我一直在尝试在我的 Windows 和 Windows Phone 8.1 应用程序上为原始推送通知实现 BackgroundTask,但它似乎不起作用。我已经成功地让基于 toast 的推送通知正常工作,但据我所知,Raw 通知会默默地将数据推送到应用程序,由应用程序显示 toast 通知或更新应用程序的磁贴。
我查看了 BackgroundTask Sample 并完全按照它进行操作,但没有任何效果(https://code.msdn.microsoft.com/windowsapps/Background-Task-Sample-9209ade9)。
这是我采取的步骤
- 在与我的其他项目相同的解决方案中创建了一个 Windows 运行时组件项目(称为 NotificationServer)
- 将类重命名为 RawTask.cs 并实现
IBackgroundTask
及其Run
方法 创建了一个方法来创建一个 toast 通知
私人无效发送通知(字符串文本){ XmlDocument toastXml = ToastNotificationManager.GetTemplateContent(ToastTemplateType.ToastText01);
XmlNodeList elements = toastXml.GetElementsByTagName("text"); foreach (IXmlNode node in elements) { node.InnerText = text; } ToastNotification notification = new ToastNotification(toastXml); ToastNotificationManager.CreateToastNotifier().Show(notification); }
向 Run 方法添加代码
BackgroundTaskDeferral _deferral = taskInstance.GetDeferral();
RawNotification notification = (RawNotification)taskInstance.TriggerDetails; string content = notification.Content; // ... SendNotification("test"); // ... _deferral.Complete();
将我的应用程序清单更新为
Toast Capable = YES
和Lock Screen Notifications = Badge
添加了后台任务的声明,其中包含
Supported Task Type = Push Notification
和Entry Point = NotificationServer.RawTask
添加了注册后台任务的代码
public static BackgroundTaskRegistration RegisterBackgroundTask(string taskEntryPoint, string taskName, IBackgroundTrigger trigger, IBackgroundCondition condition) { // // 检查此后台任务的现有注册。//
foreach (var cur in BackgroundTaskRegistration.AllTasks) { if (cur.Value.Name == taskName) { // // The task is already registered. // return (BackgroundTaskRegistration)(cur.Value); } } // // Register the background task. // var builder = new BackgroundTaskBuilder(); builder.Name = taskName; builder.TaskEntryPoint = taskEntryPoint; builder.SetTrigger(trigger); if (condition != null) { builder.AddCondition(condition); } BackgroundTaskRegistration task = builder.Register(); return task; }
并执行它
var reg = RegisterBackgroundTask("NotificationServer.RawTask", "RawNotifications", new PushNotificationTrigger(), null);
我在这里缺少什么吗,我的应用程序似乎没有响应推送通知事件。我已确保我的应用程序与商店中的应用程序相关联,并且使用正确的客户端密码和应用程序 ID 发送推送。