【问题标题】:WinJS app with C# background task for push notifications带有用于推送通知的 C# 后台任务的 WinJS 应用程序
【发布时间】:2015-05-30 21:56:01
【问题描述】:

我正在尝试在 C# 中为链接到 winjs 应用程序的推送通知创建一个后台任务(在有人问之前:在 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);
}
}

但还有一些问题:

  • 如何将它集成到我的 winjs 应用程序中?添加作为参考并将其添加到我的 appxmanifest?还是我需要手动注册任务并像访问它一样

    var task = new LibraryName.myPushNotificationBgTask();

  • 当在 appxmanifest 中定义时,我能否使用此 backgroundtask 访问相同的本地设置?点击引发的通知会导致打开(正确的)应用吗?

提前致谢!

【问题讨论】:

    标签: javascript c# push-notification windows-8.1 winjs


    【解决方案1】:

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

    我建议不要从您的 JS 应用程序中实例化 C# 组件/类,因为这对于后台任务来说不是必需的,并且它应该避免不得不拉入 CLR 的重量和相关的性能/内存/等成本。

    在清单编辑器中,您需要为后台任务添加声明,并将“入口点”指定为“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(因此您可以查看是否已经注册了它/它们)、清除它们等。有一些不同的技术可以避免多次注册它们,但我猜你可以弄清楚那部分:-)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-08-15
      • 2014-03-31
      • 1970-01-01
      • 2018-08-04
      • 2020-10-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多