Search code examples
androidbluetooth-lowenergyandroid-bluetoothandroid-ble

ScanCallback onBatchScanResults is getting called indefinitly


I am trying to scan for BLE devices once I find my device or after 10 sec, I am trying to stop the scan. But for some reason the onBatchScanResults is getting called indefinitely.

I found that even after stopping the scan the onBatchScanResults will be called until the queue of scanned results are drained. But in my case it is never getting stopped. Below is the code how I am trying to achieve this.

public void scan() {
    scanner = BluetoothLeScannerCompat.getScanner();
    final ScanSettings settings = new ScanSettings.Builder()
            .setScanMode(ScanSettings.SCAN_MODE_LOW_LATENCY).setReportDelay(1000).setUseHardwareBatchingIfSupported(false).build();
    final List<ScanFilter> filters = new ArrayList<>();
    filters.add(new ScanFilter.Builder().setServiceUuid(new ParcelUuid(getFilterUUID()))
            .build());
    Log.e(TAG, "Scanning.....");
    scanner.startScan(filters, settings, scanCallback);

    mIsScanning = true;
    mHandler.postDelayed(() -> {
        if (mIsScanning) {
            showToast("Not able to find any new device.");
            stopScan();
        }
    }, SCAN_DURATION);
}

private void stopScan() {
    if (mIsScanning) {
        final BluetoothLeScannerCompat scanner = BluetoothLeScannerCompat.getScanner();
        scanner.stopScan(scanCallback);
        mIsScanning = false;
        closeWaitDialog();
}

private ScanCallback scanCallback = new ScanCallback() {
    @Override
    public void onScanResult(final int callbackType, final ScanResult result) {
        // do nothing
        stopScan();
    }

    @Override
    public void onBatchScanResults(final List<ScanResult> results) {
        Log.e(TAG, results.toString() + " mIsScanning " + mIsScanning);
        if (results.size() == 1) {
            stopScan();
            ScanResult scanResult = results.get(0);
            launchSomeActivity();
        } else if (results.size() > 1) {
            stopScan();
            showToast("Too many new devices. Please scan one device at a time.");
        } else {
            // Do nothing. As we will stop anyway stop scanning after 5 sec.
        }
    }

    @Override
    public void onScanFailed(final int errorCode) {
        // should never be called
    }
};

Any help is greatly appreciated.


Solution

  • For the sake of having an answer.

    This bug is fixed in the latest version of the library(Scanner Compact Library 1.2.0).