首页 > 解决方案 > 屏幕锁定时无法运行 ble 扫描仪

问题描述

我正在运行前台服务来扫描在手机未锁定时工作正常的 ble 设备。但是当手机被锁定时,扫描仪无法检测到附近的任何设备。手机锁定时扫描计数始终为 0。我还为我的扫描仪添加了过滤器,但仍然没有运气。寻求帮助。

//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
        }
    }

标签: androidbluetooth-lowenergybeacon

解决方案


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.


推荐阅读