Unable to run ble scanner when screen is locked

Viewed 227

Am running a foreground service to scan ble devices which is working fine when the phone is not locked. But when the phone is locked, the scanner is unable to detect any devices near by. The scanned count is always 0 when the phone is locked. I have also added the filter for my scanner but still no fortune. Looking for some help.

//adding filters of the manufacturer and the uuid

    fun startScan(){
        settings = ScanSettings.Builder()
                        .setScanMode(ScanSettings.SCAN_MODE_LOW_LATENCY)
                        .build()
    
                val builder = ScanFilter.Builder()
                builder.setManufacturerData(0x004c, byteArrayOf())
                val manufactureFilter= builder.build()
    
                val uuidBuilder = ScanFilter.Builder()
                val serviceUuidString = "f8c62883-xxxx-xxxx-xxxx-430326af8bd0"
                val serviceUuidMaskString = "FFFFFFFF-FFFF-FFFF-FFFF-FFFFFFFFFFFF"
                val parcelUuid: ParcelUuid = ParcelUuid.fromString(serviceUuidString)
                val parcelUuidMask: ParcelUuid = ParcelUuid.fromString(serviceUuidMaskString)
                uuidBuilder.setServiceUuid(parcelUuid, parcelUuidMask)
                val uuidFilter = uuidBuilder.build()
    
                filters = ArrayList<ScanFilter>()
                filters.add(manufactureFilter)
                filters.add(uuidFilter)
    
                scanLeDevice(true)
    }

//to start the ble scan for a short period

    fun scanLeDevice(enable: Boolean) {
        if (enable) {
            Log.i(TAG, "Scanning started")
            if(beaconCollectionTimer != null){
                beaconCollectionTimer?.cancel()
            }
            beaconCollectionTimer = Timer()
            beaconCollectionTimer?.schedule(object : TimerTask(){
                override fun run() {
                    scanLeDevice(false)
                }
    
            },  SCANNING_INTERVEL)
    
            bluetoothAdapter.getBluetoothLeScanner()
                .startScan(filters, settings, mScanCallback)
    
        } else {
            Log.i(TAG, "scanning stopped")
            if (bluetoothAdapter.getBluetoothLeScanner() != null) {
                bluetoothAdapter.getBluetoothLeScanner().stopScan(mScanCallback)
            }
            isScanning = false
        }
    }
1 Answers

After trying various libraries to get my scanner work properly, I realized that the issue is not in the code but with the battery saver. All I did is removed the app from the battery optimization apps list and my scanner started working as expected. Even after the screen is locked am able to run the bleScanner and detect the near by devices.

Related