Android bluetoothLeScanner doesn't stop scanning for devices

1k Views Asked by At

I am trying to develope an app, which needs to scan for BLE Advertisement packets. I am receiving packets from nearby devices, but I can't stop the scan.

A similar question was already posted here: BluetoothAdapter won't stop scanning for BLE devices, but the answers don't seem to agree on eachother and suggested solutions are not working for me.

After checking the permissions I am calling the startScan() and stopScan() functions as follows:

            if (!scanning) {
                // Stops scanning after a pre-defined scan period.
                Handler(Looper.getMainLooper()).postDelayed({
                    scanning = false
                    bluetoothLeScanner.flushPendingScanResults(scanCallBackLe())
                    bluetoothLeScanner.stopScan(scanCallBackLe())
                    val mainActivityIntent = Intent(this, MainActivity::class.java)
                    this.startActivity(mainActivityIntent)
                }, SCAN_PERIOD)
                scanning = true
                bluetoothLeScanner.startScan(scanCallBackLe())
            } else {
                scanning = false
                bluetoothLeScanner.stopScan(scanCallBackLe())
            }

and my scanCallBack:

    private fun scanCallBackLe() = object : ScanCallback() {
        override fun onScanResult(callbackType: Int, result: ScanResult) {
            super.onScanResult(callbackType, result)
            println(result.scanRecord?.bytes?.toHexString())
            scanResults.add(result)
            listItems.add(result.scanRecord?.bytes?.toHexString()!!)
            adapter.notifyDataSetChanged()
        }

        override fun onScanFailed(errorCode: Int) {
            super.onScanFailed(errorCode)
            Log.d("ScanResult", "Scan failed code: $errorCode")
        }

The Activity is changing after the SCAN_PERIOD as it should from the postDelayed() function, but it doesn't stop the scanning and since I only want to scan for some time I don't want to just ignore the new incoming scan results.

Am I using the functions incorrect or doing something different wrong?

0

There are 0 best solutions below