且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

UWP 未配对的蓝牙设备

更新时间:2023-01-24 07:43:14

In order to find devices (Bluetooth or otherwise) you need a selector
which can be used to tell the DeviceWatcher the type of device to search for.

These selectors are basically strings identifying the type of device,
and the UWP framework provides some of them through methods on various classes.

//Gets all paired Bluetooth devices
var selector = BluetoothDevice.GetDeviceSelector();

//Gets all paired Bluetooth devices (same as above as far as I can tell)
var selector = BluetoothDevice.GetDeviceSelectorFromPairingState(true);

//Gets all unpaired Bluetooth devices
var selector = BluetoothDevice.GetDeviceSelectorFromPairingState(false);

From the samples on GitHub:

Currently Bluetooth APIs don't provide a selector to get ALL devices that are both paired and non-paired. Typically you wouldn't need this for common scenarios, but it's convenient to demonstrate the various sample scenarios.

Why we wouldn't typically need this is beyond me, but they do provide a selector which can be used to find both paired and unpaired devices:

var selector = 
        "System.Devices.Aep.ProtocolId:="{e0cbf06c-cd8b-4647-bb8a-263b43f0f974}"";

Once you have this selector you need to create an instance
of the DeviceWatcher class using a method on the DeviceInformation class:

var deviceWatcher = DeviceInformation.CreateWatcher(selector, 
                       null, DeviceInformationKind.AssociationEndpoint);

Finally you have to hook up the events so you get notified of changes:

deviceWatcher.Added += (s, i) => { //Handle the new device };
deviceWatcher.Updated += (s, i) => { //Handle the updated device };
deviceWatcher.Removed += (s, i) => { //Handle the removed device };
deviceWatcher.Completed += (s, a) => { s.Stop(); };
deviceWatcher.Stopped += (s, a) => { //Handle here };

Notice that in the Completed handler I stopped the DeviceWatcher
so it enters the Stopped state and can be started again.

Once you have the DeviceInformation you can pair as follows:

var pairingResult = 
    await i.Pairing.PairAsync(DevicePairingProtectionLevel.Encryption);

As for unpairing, you need to make sure your project targets Build 10586
or any later version in the project properties windows:

Then you'll be able to call UnPairAsync:

await i.Pairing.UnpairAsync();

Older builds do not support UnpairAsync.