我注意到在 ble 扫描器的几个实现中,扫描在给定时间段后停止并再次开始,例如每 20 秒一次。
例如,这里有一个扫描程序类在单独的线程中启动扫描程序。您可以在 start()
方法中看到线程进入睡眠状态一段时间,然后停止并重新启动扫描程序:
public class BleScanner extends Thread {
private final BluetoothAdapter bluetoothAdapter;
private final BluetoothAdapter.LeScanCallback mLeScanCallback;
private volatile boolean isScanning = false;
public BleScanner(BluetoothAdapter adapter, BluetoothAdapter.LeScanCallback callback) {
bluetoothAdapter = adapter;
mLeScanCallback = callback;
}
public boolean isScanning() {
return isScanning;
}
public void startScanning() {
synchronized (this) {
isScanning = true;
start();
}
}
public void stopScanning() {
synchronized (this) {
isScanning = false;
bluetoothAdapter.stopLeScan(mLeScanCallback);
}
}
@Override
public void run() {
try {
// Thread goes into an infinite loop
while (true) {
synchronized (this) {
// If there is not currently a scan in progress, start one
if (!isScanning) break;
bluetoothAdapter.startLeScan(mLeScanCallback);
}
sleep(Constants.SCAN_PERIOD); // Thread sleeps before stopping the scan
// stop scan
synchronized (this) {
bluetoothAdapter.stopLeScan(mLeScanCallback);
}
// restart scan on next iteration of infinite while loop
}
} catch (InterruptedException ignore) {
} finally { // Just in case there is an error, the scan will be stopped
bluetoothAdapter.stopLeScan(mLeScanCallback);
// The finally block always executes when the try block exits. This ensures that the
// finally block is executed even if an unexpected exception occurs.
}
}
}
停止和重新启动扫描仪有什么好处吗?为什么不让扫描永久继续呢?
有优点。在某些设备上,每次扫描只会看到一次来自设备的播发。在某些广告上,您会看到所有广告。此外,重新启动扫描可以清理一些低级内容,并且通常比始终保持扫描程序处于活动状态要好。