【发布时间】:2021-09-24 23:04:34
【问题描述】:
每当我从 UWP 应用程序启动 BluetoothLEAdvertisementWatcher 时,它的状态都会中止。在控制台应用程序中使用相同的功能是没有问题的(包括所需的库)。当我想与 BLE 设备配对时,我使用 UWP 应用程序中的 DeviceWatcher 没有问题。操作系统为Win10,使用VS2015 Community。
为了说明这个问题,我制作了一个 UWP 项目,其中包含蓝牙功能:
<Capabilities>
<Capability Name="internetClient" />
<DeviceCapability Name="bluetooth" />
</Capabilities>
MainPage 上有用于显示BluetoothLEAdvertisementWatcher 状态的Start、Stop 和View 按钮和TextBlock。代码呈现:
public sealed partial class MainPage : Page
{
private BluetoothLEAdvertisementWatcher watcher = null;
public MainPage()
{
this.InitializeComponent();
watcher = new BluetoothLEAdvertisementWatcher();
watcher.ScanningMode = BluetoothLEScanningMode.Active;
textBlock.Text = watcher.Status.ToString();
}
protected override void OnNavigatedTo(NavigationEventArgs e)
{
watcher.Received += OnAdvertisementReceived;
watcher.Stopped += OnAdvertisementWatcherStopped;
}
private void StopButton_Click(object sender, RoutedEventArgs e)
{
watcher.Stop();
}
private async void OnAdvertisementReceived(BluetoothLEAdvertisementWatcher watcher, BluetoothLEAdvertisementReceivedEventArgs eventArgs)
{
await this.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
{
textBlock.Text = "rcvd" + watcher.Status.ToString();
});
}
private async void OnAdvertisementWatcherStopped(BluetoothLEAdvertisementWatcher watcher, BluetoothLEAdvertisementWatcherStoppedEventArgs eventArgs)
{
// Notify the user that the watcher was stopped
await this.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
{
textBlock.Text = "stopped:" + watcher.Status.ToString();
});
}
private void buttonStart_Click(object sender, RoutedEventArgs e)
{
watcher.Start();
textBlock.Text = watcher.Status.ToString();
}
private void buttonStop_Click(object sender, RoutedEventArgs e)
{
watcher.Stop();
textBlock.Text = watcher.Status.ToString();
}
private void buttonView_Click(object sender, RoutedEventArgs e)
{
textBlock.Text = watcher.Status.ToString();
}
}
程序启动时,BluetoothLEAdvertisementWatcher 状态为 Created。按下 Start 按钮后,watcher 启动,但状态变为 Aborted,并触发事件 OnAdvertisementWatcherStopped(状态仍为 Aborted)。
对于克服这个问题有什么建议吗?或者可以做些什么来澄清问题?
更新
应用程序在不同的笔记本电脑上执行。结果是一样的,所以不是硬件问题。
网上有两个建议:
启用蓝牙(Dmitry 在第一个回答中建议)
检查功能( https://keyoti.com/blog/bluetooth-low-energy-in-windows-10-troubleshooting-capabilities/)
没有提供结果。
补充说明:当 Stopped 的事件注册被移除时, (// watcher.Stopped += OnAdvertisementWatcherStopped;) 第一个结果是 Started。下一次单击按钮 View 将显示 Aborted。在很短的时间内,结果成功有效。
任何配置设置建议?
【问题讨论】: