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

Fel*_*ino 6 c# silverlight windows-phone-8.1

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

有提示吗?

Rom*_*asz 22

在MSDN上很好地解释注册BackgroundTask.

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

    1. BackgroungTask必须是Windows Runtime Componenet(无论您的App是运行时还是Silverlight).要添加新的,请在VS的" 解决方案资源管理器"窗口中右键单击解决方案,Add然后New project选择" Windows运行时组件".

    winRTcomponent

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

    addreference

    3. DeclarationsPackage.appxmanifest文件中指定- 您需要添加Backgorund任务,标记Timer并为任务指定入口点.该切入点将是Namespace.yourTaskClass(实现IBackgroundTask) -增加的Windows运行时组件.

    宣言

    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));
          }
       }
     }
    
    Run Code Online (Sandbox Code Playgroud)

    5.最后,让我们在主项目中注册我们的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();
    }
    
    Run Code Online (Sandbox Code Playgroud)

编译,运行它应该工作.正如您所看到的,任务应该在15分钟后开始(此时间可能因操作系统在特定时间间隔内安排任务而变化,因此它将在15-30分钟之间启动).但是如何更快地调试任务?

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

跑得更快

在这里,您可以下载我的示例代码 - WP8.1 Silverlight App.