Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

BluetoothAdapter won't stop scanning for BLE devices

In my app i have start and stop button, when user press start i call startScan method

bluetoothAdapter.getBluetoothLeScanner().startScan(getLeScanCallback());

When user press stop i call stopScan however it doesn't seem to do anything. BluetoothAdapter keeps scanning for new devices.

bluetoothAdapter.getBluetoothLeScanner().stopScan(getLeScanCallback());

Here is my getLeScanCallback method:

private ScanCallback getLeScanCallback(){
    ScanCallback leScanCallback = new ScanCallback() {
        @Override
        public void onScanResult(int callbackType, ScanResult result) {
            super.onScanResult(callbackType, result);
            boolean duplicate = false;
            for(Device d : devices) {
                if(d.getAddress().equals(result.getDevice().getAddress()))
                    duplicate = true;
            }
            if(!duplicate) {
                Device device = new Device();
                device.setName(result.getDevice().getName());
                device.setAddress(result.getDevice().getAddress());
                device.setStatus(getString(R.string.disconnected));
                devices.add(device);
                deviceListAdapter.notifyDataSetChanged();
            }
        }

        @Override
        public void onBatchScanResults(List<ScanResult> results) {
            super.onBatchScanResults(results);
        }

        @Override
        public void onScanFailed(int errorCode) {
            super.onScanFailed(errorCode);
        }
    };

    return leScanCallback;
}

It gets called even after stopScan() was called. What am I doing wrong or in other words, how to stop scanning for BLE devices?

like image 617
Michał Witanowski Avatar asked Jan 31 '17 10:01

Michał Witanowski


1 Answers

Every time you call getLeScanCallback you create new instance of ScanCallback and lost reference to previous instance.

stopScan stops ongoing scan regardless what instance you pass BUT if it is a different instance (than the one you used to start) it will not remove old instance of callback so still some events will be delivered to it before it stops.

like image 118
RadekJ Avatar answered Sep 21 '22 05:09

RadekJ