咨询UWP平台监听任意蓝牙设备连接与断开状态的可用API
监听UWP中所有蓝牙设备的连接状态变化
可以通过UWP的Windows.Devices.Bluetooth和Windows.Devices.Enumeration API实现全局蓝牙设备连接/断开状态的监听,具体实现方案如下:
核心实现逻辑
- 创建蓝牙设备监听器:使用
DeviceInformation.CreateWatcher生成针对全系统蓝牙设备的监听器,通过筛选条件覆盖所有蓝牙设备(含已配对、未配对设备)。 - 处理设备生命周期:监听
DeviceWatcher的Added、Removed事件,在设备添加时为其绑定连接状态监听,设备移除时清理绑定的事件避免内存泄漏。 - 捕获连接状态变更:为每个
BluetoothDevice实例订阅ConnectionStatusChanged事件,通过BluetoothDevice.ConnectionStatus属性获取当前连接/断开状态。
关键代码示例
using Windows.Devices.Bluetooth; using Windows.Devices.Enumeration; private DeviceWatcher _bluetoothDeviceWatcher; // 初始化蓝牙设备监听器 public void InitBluetoothStatusListener() { // 生成蓝牙设备筛选器 string bluetoothSelector = BluetoothDevice.GetDeviceSelector(); _bluetoothDeviceWatcher = DeviceInformation.CreateWatcher(bluetoothSelector); // 绑定设备添加/移除事件 _bluetoothDeviceWatcher.Added += OnBluetoothDeviceAdded; _bluetoothDeviceWatcher.Removed += OnBluetoothDeviceRemoved; // 启动监听器 _bluetoothDeviceWatcher.Start(); } private async void OnBluetoothDeviceAdded(DeviceWatcher sender, DeviceInformation deviceInfo) { // 获取蓝牙设备实例 BluetoothDevice targetDevice = await BluetoothDevice.FromIdAsync(deviceInfo.Id); if (targetDevice != null) { // 绑定连接状态变更事件 targetDevice.ConnectionStatusChanged += OnBluetoothConnectionStatusChanged; // 可立即获取当前设备连接状态 var currentStatus = targetDevice.ConnectionStatus; } } private void OnBluetoothDeviceRemoved(DeviceWatcher sender, DeviceInformationUpdate deviceUpdate) { // 根据设备ID定位对应BluetoothDevice实例,取消事件绑定以避免内存泄漏 } private void OnBluetoothConnectionStatusChanged(BluetoothDevice sender, object args) { var connectionStatus = sender.ConnectionStatus; if (connectionStatus == BluetoothConnectionStatus.Connected) { // 执行设备连接后的业务逻辑 } else if (connectionStatus == BluetoothConnectionStatus.Disconnected) { // 执行设备断开后的业务逻辑 } } // 资源清理 public void DisposeBluetoothListener() { if (_bluetoothDeviceWatcher != null) { _bluetoothDeviceWatcher.Stop(); _bluetoothDeviceWatcher.Added -= OnBluetoothDeviceAdded; _bluetoothDeviceWatcher.Removed -= OnBluetoothDeviceRemoved; } }
注意事项
- 权限配置:需要在
Package.appxmanifest中添加bluetooth功能权限,否则应用无法访问蓝牙设备。 - 版本兼容性:该方案支持Windows 10 1511及以上版本,若需兼容更早版本需调整实现逻辑。
- 内存管理:务必在设备移除时取消
ConnectionStatusChanged事件的订阅,防止内存泄漏。
内容的提问来源于stack exchange,提问作者Damon Pan
相关产品推荐
相关产品推荐

