我正在编写一个BLE扫描器,它经常扫描外围设备,连接和断开连接。
我正在“循环”扫描-将其关闭2秒钟,然后再打开10秒钟-因为我在某处(会尝试查找参考)读到(否则将查找参考),否则该操作系统(在Android 7.0之后)将停止扫描在大约30分钟后在后台显示。我也经历了这样的事情。
问题是,在某些设备上(例如,摩托罗拉Moto Z和Google Pixel),出现错误SCAN_FAILED_ALREADY_STARTED,表明该应用程序已经开始使用这些参数进行扫描。
但是,使用我的扫描算法,我强制要求stopScan
在尝试startScan之前必须 进行调用。这是一个相关的代码示例,该代码示例在提到的设备上产生了错误。这只是代码的扫描部分。
private final int SCANNER_DOWN_TIME = 2000;
private final int SCANNER_LIFETIME_MS = 10000;
private Runnable runnable = new Runnable() {
private BluetoothLeScanner scanner;
final ScanSettings.Builder builder = new ScanSettings.Builder();
final ScanSettings settings = builder.setScanMode(ScanSettings.SCAN_MODE_LOW_LATENCY)
.build();
public void run() {
try {
bootScanner();
} catch (Exception e) {
Sentry.capture(e);
}
}
class StartScannerAndScheduleReboot implements Runnable {
@Override
public void run() {
if (bluetoothAdapter.isEnabled()) {
scanner = bluetoothAdapter.getBluetoothLeScanner();
if (scanner != null) {
scanner.startScan(null, settings, sensorReadingHandler);
}
} else {
bluetoothAdapter.enable();
}
bootScanHandler = new Handler(Looper.getMainLooper());
bootScan = new RebootScanner();
bootScanHandler.postDelayed(bootScan, SCANNER_LIFETIME_MS);
}
}
class RebootScanner implements Runnable {
@Override
public void run() {
bootScanner();
}
}
private void bootScanner() {
try {
scanner.stopScan(sensorReadingHandler);
} catch (Exception e) {
/* We can ignore this - there are cases that this will happen & it's ok */
}
startScanHandler = new Handler(Looper.getMainLooper());
startScan = new StartScannerAndScheduleReboot();
startScanHandler.postDelayed(startScan, SCANNER_DOWN_TIME);
}
private ScanCallback sensorReadingHandler = new ScanCallback()
{ /* I don't believe the scanCallback code is relevant, as this happens before any connections are even attempted. */ }
};
毫不奇怪,该应用程序仍然能够读取BLE传输,但其中一些被丢弃。这使我相信我不应该只忽略此错误。