在Silverlight 8.1应用程序中注册后台任务

6
我正在开发一款使用BLE与设备进行通信的应用程序,我需要接收来自它的后台通知。我知道存在GattCharacteristicNotificationTrigger,但我找不到在Silverlight 8.1应用程序中注册后台任务的方法。
有什么提示吗?
1个回答

22

MSDN上,很好地解释了如何注册一个BackgroundTask

这里是一个简单的示例,它在TimeTrigger触发时显示Toast,步骤如下(适用于运行时和Silverlight应用程序):

    1. 背景任务必须是Windows Runtime组件(无论您的应用程序是Runtime还是Silverlight)。要添加新组件,请右键单击VS中的解决方案资源管理器窗口中的解决方案,选择添加,然后选择新建项目并选择Windows Runtime组件

winRTcomponent

    2. 在主项目中添加引用。

addreference

    3. 在Package.appxmanifest文件中指定Declarations - 您需要添加一个Backgorund Task,标记Timer并为任务指定Entry PointEntry Point将是一个Namespace.yourTaskClass(它实现了IBackgroundTask) - 添加的Windows Runtime组件。

declaration

    4. 您的BackgroundTask可能是什么样子? - 假设我们想要从中发送Toast(当然还可以有很多其他功能):

namespace myTask // the Namespace of my task 
{
   public sealed class FirstTask : IBackgroundTask // sealed - important
   {
      public void Run(IBackgroundTaskInstance taskInstance)
      {
        // simple example with a Toast, to enable this go to manifest file
        // and mark App as TastCapable - it won't work without this
        // The Task will start but there will be no Toast.
        ToastTemplateType toastTemplate = ToastTemplateType.ToastText02;
        XmlDocument toastXml = ToastNotificationManager.GetTemplateContent(toastTemplate);
        XmlNodeList textElements = toastXml.GetElementsByTagName("text");
        textElements[0].AppendChild(toastXml.CreateTextNode("My first Task"));
        textElements[1].AppendChild(toastXml.CreateTextNode("I'm message from your background task!"));
        ToastNotificationManager.CreateToastNotifier().Show(new ToastNotification(toastXml));
      }
   }
 }

    5. 最后,在主项目中注册我们的后台任务

private async void Button_Click(object sender, RoutedEventArgs e)
{
    // Windows Phone app must call this to use trigger types (see MSDN)
    await BackgroundExecutionManager.RequestAccessAsync();

    BackgroundTaskBuilder taskBuilder = new BackgroundTaskBuilder { Name = "First Task", TaskEntryPoint = "myTask.FirstTask" };
    taskBuilder.SetTrigger(new TimeTrigger(15, true));
    BackgroundTaskRegistration myFirstTask = taskBuilder.Register();
}

编译、运行,就可以正常工作了。如您所见,任务应该在 15 分钟后开始(这个时间可能会因为操作系统安排任务的特定间隔而有所变化,所以它将在 15-30 分钟之间启动)。但是如何更快地调试任务呢?

有一种简单的方法——进入 Debug location 工具栏,你会看到一个下拉菜单 Lifecycle events,从中选择你的任务,它就会触发(有时需要打开/关闭下拉菜单进行刷新)。

run faster

在这里可以下载 我的示例代码——WP8.1 Silverlight 应用程序。


1
刚试了一下,可以用,不知道,我会在主项目上重试(昨晚我尝试过,当时很困:P),谢谢 :) - Fela Ameghino
1
很好的答案,喜欢这些图片。 - D.Rosado
@Romasz 很有用的帖子,但是除了这个话题之外还有一个问题。如何处理取消的后台任务?如果应用程序在 Windows Phone 8.1 的电池节能模式中被允许停止。我需要检测后台任务何时被取消,以便我可以调用另一个函数。我已经查阅并在我的项目中实现了后台任务,https://msdn.microsoft.com/en-us/library/windows/apps/xaml/hh977052.aspx?f=255&MSPPError=-2147217396 但我仍然无法检测到后台任务是否被取消了?你能帮我吗? - Balasubramani M
@Romasz 是的,我已经添加了。但是 OnCanceled 方法没有被调用。这就是我的问题所在。 - Balasubramani M
最好的方法是从注册BTask的应用程序中取消它。 - Romasz
显示剩余10条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接