You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

UWP中如何通过服务GUID筛选蓝牙设备(使用DeviceWatcher)

UWP 筛选特定服务GUID蓝牙设备的两种实现方案

一、直接创建带服务筛选的DeviceWatcher(系统层面过滤)

这种方式通过**高级查询语法(AQS)**直接指定目标服务GUID,让系统仅返回符合条件的设备,无需处理无关设备事件,效率更高。

代码示例

// 替换为你需要过滤的目标服务GUID
string targetServiceGuid = "0000180d-0000-1000-8000-00805f9b34fb";
// 构造AQS筛选字符串,匹配指定服务ID
string aqsFilter = $"System.Devices.AepService.ServiceId:=\"{{{targetServiceGuid}}}\"";

// 创建仅监听符合该服务的设备Watcher
DeviceWatcher watcher = DeviceInformation.CreateWatcher(
    aqsFilter,
    // 指定需要获取的设备属性(按需添加)
    new string[] { "System.Devices.Aep.DeviceAddress", "System.Devices.Aep.IsConnected" },
    DeviceInformationKind.AssociationEndpointService
);

// 注册设备事件回调
watcher.Added += (sender, args) =>
{
    // 处理找到的符合条件的设备
    DeviceInformation deviceInfo = args.DeviceInformation;
    // ... 你的业务逻辑
};
watcher.Updated += Watcher_Updated;
watcher.Removed += Watcher_Removed;

// 启动Watcher
watcher.Start();

注意点

部分蓝牙设备可能不会完整广播所有支持的服务,可能导致符合条件的设备被系统过滤掉,适合服务广播规范的场景。

二、设备发现后再筛选(应用层过滤)

如果系统层面的筛选存在漏检情况,可以先扫描所有蓝牙设备,再在应用层检查设备是否包含目标服务GUID,兼容性更强。

代码示例

// 创建通用蓝牙设备扫描Watcher(包含未配对设备)
DeviceWatcher watcher = DeviceInformation.CreateWatcher(
    BluetoothDevice.GetDeviceSelectorFromPairingState(false),
    // 必须请求ServiceIds属性,用于后续筛选
    new string[] { "System.Devices.Aep.ServiceIds" },
    DeviceInformationKind.AssociationEndpoint
);

watcher.Added += async (sender, args) =>
{
    DeviceInformation deviceInfo = args.DeviceInformation;
    // 尝试获取设备支持的所有服务ID列表
    if (deviceInfo.Properties.TryGetValue("System.Devices.Aep.ServiceIds", out object serviceIdsObj))
    {
        var serviceIds = serviceIdsObj as IEnumerable<string>;
        string targetServiceGuid = "0000180d-0000-1000-8000-00805f9b34fb";
        // 检查是否包含目标服务GUID(注意格式带大括号)
        if (serviceIds?.Contains($"{{{targetServiceGuid}}}") == true)
        {
            // 转换为BluetoothDevice对象进行后续操作
            BluetoothDevice targetDevice = await BluetoothDevice.FromIdAsync(deviceInfo.Id);
            // ... 你的业务逻辑
        }
    }
};

// 启动扫描
watcher.Start();

权限声明

需要在Package.appxmanifest中添加蓝牙相关权限,否则无法获取设备服务信息:

<Capabilities>
    <DeviceCapability Name="bluetooth" />
    <!-- 如果需要访问特定服务,添加对应的服务权限 -->
    <DeviceCapability Name="bluetooth.genericAttributeProfile">
        <Device Id="any">
            <Function Type="serviceId:0000180d-0000-1000-8000-00805f9b34fb" />
        </Device>
    </DeviceCapability>
</Capabilities>

内容的提问来源于stack exchange,提问作者Brudi_Voeller

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.30 09:10:00