1

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?

  • I don't really know kotlin that much but I think your scanCallBackLe variable should be an object, not a function returning an object. Otherwise you try to stop a newly created callback object which will not be matched with the previous one. So the accepted answer in that other question is what your problem is. – Emil May 22 '22 at 20:42
  • @Emil Ok that makes sense. For some reason I have not thought about it. But thank you! It works now. – HappyLittleAccident May 23 '22 at 09:21

0 Answers0