我正在开发一款使用BLE与设备进行通信的应用程序,我需要接收来自它的后台通知。我知道存在
有什么提示吗?
GattCharacteristicNotificationTrigger
,但我找不到在Silverlight 8.1应用程序中注册后台任务的方法。有什么提示吗?
GattCharacteristicNotificationTrigger
,但我找不到在Silverlight 8.1应用程序中注册后台任务的方法。在MSDN上,很好地解释了如何注册一个BackgroundTask。
这里是一个简单的示例,它在TimeTrigger触发时显示Toast,步骤如下(适用于运行时和Silverlight应用程序):
Namespace.yourTaskClass
(它实现了IBackgroundTask
) - 添加的Windows Runtime组件。
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 分钟之间启动)。但是如何更快地调试任务呢?
有一种简单的方法——进入 Debug location 工具栏,你会看到一个下拉菜单 Lifecycle events,从中选择你的任务,它就会触发(有时需要打开/关闭下拉菜单进行刷新)。
在这里可以下载 我的示例代码——WP8.1 Silverlight 应用程序。