具有用于推送通知的 C# 后台任务的 WinJS 应用程序

WinJS app with C# background task for push notifications

我正在尝试在链接到 winjs 应用程序的 C# 中为推送通知创建一个后台任务(在有人问之前:在 js 中不这样做的原因是因为 windows phone 运行时,参见 here)。

这是我的初稿:

public sealed class myPushNotificationBgTask : IBackgroundTask {

public void Run(IBackgroundTaskInstance taskInstance)
{
    RawNotification notification = (RawNotification)taskInstance.TriggerDetails;
    string content = notification.Content;

    Debug.WriteLine("received push notification from c# bg task!");

    var settings = ApplicationData.Current.LocalSettings;
    settings.Values["push"] = content;

    raiseToastNotification(content);
}

private void raiseToastNotification(string text)
{
    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);
}
}

但还有一些问题:

提前致谢!

通常,您会通过将 C# 后台任务项目作为同一 VS 解决方案的一部分来执行此操作,然后将 JS 应用程序项目的引用添加到后台任务项目。

我建议 不要 从你的 JS 应用实例化 C# component/class,因为这对于后台任务来说不是必需的,并且应该避免拉取在 CLR 的权重和相关成本中 performance/memory/etc.

在清单编辑器中,您需要为后台任务添加声明,并将 "Entry point" 指定为 "LibraryName.myPushNotificationBgTask"。不要为可执行文件或起始页字段指定任何内容。

在您的 JS 代码中(可能在应用程序启动后不久),您需要注册该任务。例如:

var bg = Windows.ApplicationModel.Background;
var taskBuilder = new bg.BackgroundTaskBuilder();
var trigger = new bg.PushNotificationTrigger();
taskBuilder.setTrigger(trigger);
// Must match class name and registration in the manifest
taskBuilder.taskEntryPoint = "LibraryName.myPushNotificationBgTask";
taskBuilder.name = "pushNotificationBgTask";
taskBuilder.register();

还有用于枚举任务的 API(因此您可以查看您是否已经注册 it/them)、清除它们等。有一些不同的技术可以避免多次注册它们,但我我猜你能弄清楚那部分:-)