Right now I'm developing client application for Android that works with physical locks with our controllers. User can open lock via Bluetooth using this application (connection -> secure session creation -> sending some user key). All works fine except one feature: opening lock when Android device screen is off. I am using following approach: Foreground service that periodically scans for nearby BLE devices and when scan is successful (nearby lock device found using BLE filters), application tries to connect and send lock key to lock device. So, there are two problems:
- Android kills foreground service in few minutes after screen off. After setting ignore battery optimization it works ok, however I can't find universal way to navigate user to those settings (because those settings are vendor specific, see https://dontkillmyapp.com/ and android open battery settings programically).
- Background limits for BLE scanning are tricky.
I know one application that achieved same thing without foreground service: https://play.google.com/store/apps/details?id=eu.hoermann.ast.bluesecur, this application seems to work good in background without user interaction with battery usage optimization menu.
So, question is: what is the best way to trigger background process (device screen is turned off) when nearby suitable BLE device available?
CodePudding user response:
I think you shoul add a wake lock with the service:
https://developer.android.com/training/scheduling/wakelock
https://developer.android.com/training/scheduling/wakelock#cpu
CodePudding user response:
Your requirements perfectly describe the scenario of a companion app. Disadvantage: it is only available from Android 12 (API level 31) onwards.