BluetoothLEAdvertisementWatcher无法正常工作

时间:2016-07-26 17:48:26

标签: windows

我有Windows 10 Pro,在HP ZBook G2上构建10586.494。当我去设置 - >设备 - >蓝牙和蓝牙开关,我可以看到附近的BLE设备(它们是我公司生产的定制BLE设备)。

我想在通用Windows应用程序(在Visual Studio 2015中)中与我的BLE设备进行交互。我使用这段代码(它只是一段代码)

BluetoothLEAdvertisementWatcher watcher;
//....
    watcher = new BluetoothLEAdvertisementWatcher { ScanningMode = BluetoothLEScanningMode.Active };
    watcher.Received += WatcherOnReceived;
    watcher.Start();
//....
    private void WatcherOnReceived(BluetoothLEAdvertisementWatcher sender, BluetoothLEAdvertisementReceivedEventArgs btAdv)
    {
    }

当我运行此应用程序时,WatcherOnReceived永远不会执行(尽管执行了watcher.Start)。为什么以及如何解决它?

2 个答案:

答案 0 :(得分:0)

我必须在设置中打开蓝牙 - >设备 - >蓝牙,以便在我的应用程序中接收广告。

答案 1 :(得分:0)

如果找到了更好的解决方法。 (我正在使用Win 10 1803。)

首先,由于最初的问题尚不完全清楚,所以要重述该问题:

  • 如果BLE设备在watcher.Start()之前做广告,BluetoothLEAdvertisementWatcher可以工作
  • 如果BLE设备在watcher.Start()之后开始投放广告,BluetoothLEAdvertisementWatcher将不起作用
  • 如果watcher.Start()之后BluetoothLEAdvertisementWatcher不起作用,则它将在Windows 10蓝牙设置打开或关闭时开始工作(即,打开或关闭设置窗口会触发BluetoothLEAdvertisementWatcher开始工作)

因此,我想出的解决方法是继续在后台启动和停止第二个BluetoothLEAdvertisementWatcher,以创建与Windows Bluetooth设置窗口相同的触发器。

例如,使用WinForms计时器:

... 
var timer = new Timer { Interval = 1000 };
timer.Tick += Timer_Tick;
timer.Start();
...

private void Timer_Tick(object sender, EventArgs e)
{
  var watcher = new BluetoothLEAdvertisementWatcher();
  watcher.Received += (s, a) => { };
  watcher.Start();
  Task.Delay(500).ContinueWith(_ => watcher.Stop());
}