为什么蓝牙低能量扫描仪需要重新启动?

时间:2017-05-26 00:28:55

标签: bluetooth bluetooth-lowenergy

我注意到在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.
        }
    }
}

停止并重新启动扫描仪有什么好处吗?为什么不让扫描一直持续下去?

1 个答案:

答案 0 :(得分:1)

有优点。在某些设备上,每次扫描只能看到设备上的广告。在某些你会看到所有广告。此外,重新启动扫描会清除一些低级别的内容,并且通常比始终保持扫描程序处于活动状态更好。