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

时间:2014-06-05 21:16:44

标签: c# silverlight windows-phone-8.1

我正在开发一个使用BLE与项目进行通信的应用程序,我需要从中接收背景通知。我知道GattCharacteristicNotificationTrigger的存在,但我找不到任何方法在Silverlight 8.1应用程序中注册后台任务。

任何提示?

1 个答案:

答案 0 :(得分:22)

BackgroundTask已经很好地解释了注册here at MSDN

以下是TimeTrigger触发并显示Toast的简单示例,步骤(适用于RunTime和Silverlight应用程序):

    1。 BackgroungTask必须是Windows Runtime Componenet(无论您的App是运行时还是Silverlight)。要添加新的,请在VS的 Solution Explorer 窗口中右键单击解决方案,选择添加然后新项目并选择 Windows运行时组件

    winRTcomponent

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

    addreference

    3。在 Package.appxmanifest 文件中指定声明 - 您需要添加 Backgorund任务,标记计时器并指定入口点。 入口点将是Namespace.yourTaskClass(实现IBackgroundTask) - 添加的Windows运行时组件。

    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。最后,让我们在主项目中register our BackgroundTask

    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分钟之间启动)。但是如何更快地调试任务?

有一种简单的方法 - 转到调试位置工具栏,您将看到一个下拉列表生命周期事件,从中选择您的任务并将触发(有时打开/关闭下拉菜单刷新它)。

run faster

Here you can download我的示例代码 - WP8.1 Silverlight App。

相关问题