我正在开发一个使用BLE与项目进行通信的应用程序,我需要从中接收背景通知。我知道GattCharacteristicNotificationTrigger
的存在,但我找不到任何方法在Silverlight 8.1应用程序中注册后台任务。
任何提示?
答案 0 :(得分:22)
BackgroundTask已经很好地解释了注册here at MSDN。
以下是TimeTrigger触发并显示Toast的简单示例,步骤(适用于RunTime和Silverlight应用程序):
Namespace.yourTaskClass
(实现IBackgroundTask
) - 添加的Windows运行时组件。
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));
}
}
}
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分钟之间启动)。但是如何更快地调试任务?
有一种简单的方法 - 转到调试位置工具栏,您将看到一个下拉列表生命周期事件,从中选择您的任务并将触发(有时打开/关闭下拉菜单刷新它)。
Here you can download我的示例代码 - WP8.1 Silverlight App。