Flutter蓝牙开发:扫描时仅显示指定MAC地址的设备
实现蓝牙扫描仅显示特定MAC前缀的设备
你可以通过在onScanResult方法中添加MAC地址过滤逻辑,只处理符合条件的设备,具体修改如下:
修改后的代码
private ScanCallback getScanCallback21() { if (scanCallback21 == null) { scanCallback21 = new ScanCallback() { @Override public void onScanResult(int callbackType, ScanResult result) { super.onScanResult(callbackType, result); BluetoothDevice device = result.getDevice(); // 先过滤MAC地址,仅保留包含"OO:FE"的设备 if (device == null || device.getAddress() == null || !device.getAddress().contains("OO:FE")) { return; } // 原有去重逻辑,仅处理未扫描过的设备 if (!allowDuplicates && result != null) { if (macDeviceScanned.contains(device.getAddress())) return; macDeviceScanned.add(device.getAddress()); } // 将符合条件的设备发送到Flutter端 Protos.ScanResult scanResult = ProtoMaker.from(device, result); invokeMethodUIThread("ScanResult", scanResult.toByteArray()); } @Override public void onBatchScanResults(List<ScanResult> results) { super.onBatchScanResults(results); // 批量扫描结果也添加相同过滤逻辑 for (ScanResult result : results) { BluetoothDevice device = result.getDevice(); if (device == null || device.getAddress() == null || !device.getAddress().contains("OO:FE")) { continue; } if (!allowDuplicates && !macDeviceScanned.contains(device.getAddress())) { macDeviceScanned.add(device.getAddress()); Protos.ScanResult scanResult = ProtoMaker.from(device, result); invokeMethodUIThread("ScanResult", scanResult.toByteArray()); } } } }; } return scanCallback21; }
关键修改说明
- 在处理扫描结果前,先判断设备MAC地址是否包含
"OO:FE",不符合条件的直接跳过,不进入后续流程 - 调整了原有去重逻辑的顺序,确保只有符合条件的设备才会被加入去重列表
- 给批量扫描结果
onBatchScanResults也添加了相同的过滤逻辑,避免遗漏批量返回的设备
内容的提问来源于stack exchange,提问作者rania
相关产品推荐
相关产品推荐

