How do you get a BLE Advertisment callback in a de

2019-05-19 13:56发布

I am trying to get a BLE advertisement callback from a .NET Windows desktop application. I am able to call into the APIs, however the Received event is never called from the OS in a WPF or Command line application. I do get events when the code is called from a Unit Test in VS2015, or universal Windows app. However, I need to do other things not available in universal Windows. Here is the code:

    using Windows.Devices.Bluetooth.Advertisement;
    public static void ScanForAdvertisments()
    {
        mWatcher = new BluetoothLEAdvertisementWatcher();           
        mWatcher.Received += OnAdvertismentReceived;
        mWatcher.ScanningMode = BluetoothLEScanningMode.Active;
        mWatcher.Start();
    }

    public static void OnAdvertismentReceived(BluetoothLEAdvertisementWatcher sender, BluetoothLEAdvertisementReceivedEventArgs args)
    {

        ulong address = args.BluetoothAddress;
        short rssi = args.RawSignalStrengthInDBm;
    }
  • I've referenced Windows.winmd in order to include the BLE/UWP namespaces.
  • I am using framework version 4.6.1 on Windows 10 Anniversary Edition, I had the same problem on the previous windows build as well.
  • Using a UWP app I set the DeviceCapability for bluetooth in the appxmanifest. The unit test project seems not to require this and I'm not sure how to apply appxmanifests to desktop projects.
  • The status property reports the scanner is running and the stopped event is also never triggered.

Anyway, is this a Windows bug? Is there a way to workaround it? I tried looking into app services but they seem not to be set up to call into desktop code very well and calling desktop code from UWP seems complex to deploy. Thanks.

1条回答
我欲成王,谁敢阻挡
2楼-- · 2019-05-19 14:18

Just tried this out with a Console .NET 4.6.1 app and the advertisement callback is coming through. I wrote up a GitHub Sample of this a bit ago, which might help out. They key for getting WinRT APIs working are two references:

To use the WinRT APIs, add two references:

  1. C:\Program Files (x86)\Windows Kits\10\UnionMetadata\Windows.winmd

  2. C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework.NETCore\v4.5\System.Runtime.WindowsRuntime.dll

It sounds like you may be missing the second reference. I was able to use the v4.5 .NetCore framework with 4.6.1.

查看更多
登录 后发表回答