问题
问题是你只是覆盖了onBatchScanResults
方法而不是onScanResult
方法。onBatchScanResults
仅在以下情况下才会被触发:
- 您已经设置了
ScanSettings
模式为ScanSettings.SCAN_MODE_LOW_POWER
(这是默认值)使用ScanSettings.Builder
.
- 您已使用以下命令将报告延迟时间设置为 >0 的某个值
setReportDelay(long reportDelayMillis)
在你的ScanSettings.Builder
.
报告延迟毫秒 https://developer.android.com/reference/android/bluetooth/le/ScanSettings.Builder.html#setReportDelay(long)- 报告延迟(以毫秒为单位)。设置为 0 可立即通知结果。值 > 0 会导致扫描结果排队并在请求的延迟后或内部缓冲区填满时传送。
例如:
public void startScan(BluetoothLeScanner scanner) {
ScanFilter filter = new ScanFilter.Builder().setDeviceName(null).build();
ArrayList<ScanFilter> filters = new ArrayList<ScanFilter>();
filters.add(filter);
ScanSettings settings = new ScanSettings.Builder()
.setScanMode(ScanSettings.SCAN_MODE_LOW_POWER)
.setReportDelay(1l)
.build();
Log.i(TAG,"The setting are "+settings.getReportDelayMillis());
scanner.startScan(filters,settings,BLEScan);
}
解决方案
但是,您可能只想一次获得一次结果,而不是一批结果。要实现这一点,您不必修改 ScanSettings,只需覆盖onScanResult
方法在你的ScanCallback
这样就可以了。
private ScanCallback mScanCallback =
new ScanCallback() {
public void onScanResult(int callbackType, ScanResult result) {
System.out.println(result.getDevice().getName())
// Do whatever you want
};
...
};
替代方案 - RxAndroidBle
无论如何,我强烈推荐使用该库RxAndroidBLE https://github.com/Polidea/rxandroidble。它维护得很好,并且解决了许多开箱即用的 BLE 问题(扫描可能是 BLE 中不太复杂的部分)。
使用该库,可以像这样完成扫描:
Disposable scanSubscription = rxBleClient.scanBleDevices(
new ScanSettings.Builder()
// .setScanMode(ScanSettings.SCAN_MODE_LOW_LATENCY) // change if needed
// .setCallbackType(ScanSettings.CALLBACK_TYPE_ALL_MATCHES) // change if needed
.build()
// add filters if needed
)
.subscribe(
scanResult -> {
// Process scan result here.
},
throwable -> {
// Handle an error here.
}
);
// When done, just dispose.
scanSubscription.dispose();