我正在尝试使用GattCharacteristicNotifictionTrigger注册后台任务以从 BLE 设备接收数据,但无论我做什么,应用程序在到达.Register()行时总是会引发异常。我在MSDN和其他地方参考了许多指南,我相信我正在做所有需要的事情。下面是一个清单,突出了需要什么。就后台任务而言,我什么也没做,也没少做:
1) 在 Package.appxmanifest 中设置后台任务的声明,如下所示:
<Extensions>
<Extension Category="windows.backgroundTasks" EntryPoint="AgHost.BackgroundTask">
<BackgroundTasks>
<Task Type="systemEvent" />
</BackgroundTasks>
</Extension>
<Extension Category="windows.backgroundTasks" EntryPoint="BackgroundBLEService.MyBLEService">
<BackgroundTasks>
<m3:Task Type="gattCharacteristicNotification" />
</BackgroundTasks>
</Extension>
</Extensions>
2)添加对WinRT项目的引用,该项目在我的主应用程序项目中具有后台任务(顺便说一句,这是一个Silverlight 8.1项目)
3)在后台服务类(这是一个密封的公共类)中创建一个 Run() 函数,如下所示:
public sealed class MyBLEService: IBackgroundTask
{
public void Run(IBackgroundTaskInstance taskInstance)
{
try
{
GattCharacteristicNotificationTriggerDetails details = (GattCharacteristicNotificationTriggerDetails)taskInstance.TriggerDetails;
byte[] ReceivedData = new byte[details.Value.Length];
DataReader.FromBuffer(details.Value).ReadBytes(ReceivedData);
foreach(byte b in ReceivedData)
{
Debug.WriteLine(b.ToString());
XmlDocument xml = ToastNotificationManager.GetTemplateContent(ToastTemplateType.ToastText01);
xml.SelectSingleNode("/toast/visual/binding/text").InnerText = string.Format("Value Received: " + b.ToString());
ToastNotification toast = new ToastNotification(xml);
ToastNotifier notifier = ToastNotificationManager.CreateToastNotifier();
notifier.Show(toast);
}
}
finally
{
Debug.WriteLine("Background service exception");
}
}
}
4)从我的主应用程序中注册事件,如下所示:
GattCharacteristicNotificationTrigger trigger = new GattCharacteristicNotificationTrigger(thermometerCharacteristic); //thermometerCharacteristic is defined in another block of code
await BackgroundExecutionManager.RequestAccessAsync();
BackgroundTaskBuilder BLETaskBuilder = new BackgroundTaskBuilder();
BLETaskBuilder.Name = "DataReceiveNotifier";
BLETaskBuilder.TaskEntryPoint = "BackgroundBLEService.MyBLEService";
BLETaskBuilder.SetTrigger(trigger);
App.MyBackgroundTask = BLETaskBuilder.Register();
5)确保后台任务入口点的字符串序列与后台项目的namespace.classname拼写完全匹配。我已经检查并仔细检查了 Package.appxmanifest 和我试图注册任务的主项目中的拼写。
但是当代码到达.Register()行时,我仍然会遇到第一次机会异常。有关异常的更多详细信息:
- H结果:-2147221164
- 消息:未注册类(HRESULT 异常:0x80040154 (REGDB_E_CLASSNOTREG))
知道我做错了什么吗?我在这里发现了一个类似的问题,但没有明确回答。