android - 屏幕锁定时无法运行 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
}
}
解决方案
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.
推荐阅读
- nao-robot - NAO 机器人行为无需触发即可激活
- angularjs - 如何在angularjs中更新本地json文件
- c# - 如何仅在我的网站上嵌入谷歌驱动器视频
- javascript - 如何在反应路由器 dom v4 上的嵌套路由中获取参数?
- opencv - opencv中基本颜色的关键色调值是什么
- python - aiohttp asyncio.TimeoutError 从无使用 ClientSession
- javascript - 即使数据源在环回 3 上不可用,如何保持 api 活动?
- cassandra-3.0 - 两个数据中心,每个数据中心有一个节点
- dart - Flutter Dio 不接受 int 值作为 queryParameters
- mysql - 我如何在日期中更改时间戳 mysql