我正在使用具有蓝牙功能的Xamarin.Forms构建应用程序。连接到设备后,我有ObsevableCollection
收集可用的服务。然后我想选择我正在寻找的服务。
使用Monkey.Robotics
插件,并基于示例HeartRate Monitor应用。目前,有一个
this.services = new ObservableCollection<IService> ();
listView.ItemsSource = services;
// when device is connected
adapter.DeviceConnected += (s, e) => {
device = e.Device;
// when services are discovered
device.ServicesDiscovered += (object se, EventArgs ea) => {
if (services.Count == 0) //if it's only just started
Device.BeginInvokeOnMainThread(() => {
foreach (var service in device.Services) {
services.Add(service); //add all new services found to ObservableCollection
}
});
};
// start looking for services
device.DiscoverServices ();
};
因此,当前代码检索所有服务并将它们放入ObservableCollection
,然后填充列表视图。我想搜索结果以寻找我想要的服务,而不是填充列表并等待用户输入。即
await Task.Delay (5000); // wait 5 seconds for the scan to complete
IService ChosenService = null;
try {
foreach(var data in services)
{
if (data!=null && data.ID!=null && data.ID.ToString() == 0x180D.ToString()){ ChosenService = data; break; }
}
}
catch {
Debug.WriteLine ("Exception");
}
Debug.WriteLineIf(ChosenService == null, "Not Chosen");
我已经添加了如上所示的try,catch块,并添加了检查以确保我们不使用空引用。所有这些都可以编译,应用程序在任何时候都不会崩溃!但是,该过程以ChosenService = null结束?所以这段代码不起作用。任何想法为什么不呢?服务扫描似乎正常,因为在调试窗口中,我得到以下反馈:
2015-09-26 22:09:38.329 Gas_SenseiOS[1431:605554] Device.Discovered Service: <CBService: 0x12832e7e0, isPrimary = YES, UUID = Heart Rate>
2015-09-26 22:09:38.333 Gas_SenseiOS[1431:605554] Device.Discovered Service: <CBService: 0x12831c950, isPrimary = YES, UUID = Device Information>
2015-09-26 22:09:38.349 Gas_SenseiOS[1431:605554] Device.Discovered Service: <CBService: 0x12832e7e0, isPrimary = YES, UUID = Heart Rate>
2015-09-26 22:09:38.350 Gas_SenseiOS[1431:605554] Device.Discovered Service: <CBService: 0x12831c950, isPrimary = YES, UUID = Device Information>
2015-09-26 22:09:38.352 Gas_SenseiOS[1431:605554] Device.Discovered Service: <CBService: 0x12832e7e0, isPrimary = YES, UUID = Heart Rate>
2015-09-26 22:09:38.352 Gas_SenseiOS[1431:605554] Device.Discovered Service: <CBService: 0x12831c950, isPrimary = YES, UUID = Device Information>
答案 0 :(得分:1)
从臀部拍摄我怀疑您的服务中的数据元素为null或具有空ID。 尝试
if (data!=null && data.ID!=null && data.ID.ToString() == 0x180D.ToString()){ ChosenService = data; break; }
答案 1 :(得分:0)
使用上面的所有评论,以及对BLE规范和插件编写方式的一些研究,解决方案是:
IService ChosenService = null;
try {
foreach(var data in services)
{
if (data!=null && data.Name == "Heart Rate"){ ChosenService = data; }
}
}
catch {
Debug.WriteLine ("Exception");
}