I have decided to ask this question after a research of almost 3 weeks.
The requirement is such that my app has only one background service and it has to search for BLE devices all the time. (Don't freak out I have set up a slow scanning mode when no BLE device is in range in which i pause and resume the scan). The app is not for everyone as it is meant to do some authentication with the BLE devices whenever one comes in range. Hopefully this establishes the IMPORTANCE of service running all the time. I can't use foreground service (business requirement).
Whenever android kills my service onDestroy()
is not called. So my best bet is to use an Alarm Manager which triggers every 5 minutes and checks if the service is killed and if it is killed it calls startService()
. Alarm triggers fine for some time but after random times (1, 2 3 hours) even the alarm gets killed and it doesn't trigger anymore.
I'm sending a broadcast through the alarm whose onReceive()
is responsible for starting the service if it is killed. I'm out of workarounds can any one explain or suggest why the alarm manager malfunctions after some random time. I'm currently testing my app on nexus 6p, Galaxy s7 edge, Samsung A5, Huawei P9.
Any more explanation can be provided.
If
adb shell dumpsys alarm
does not show your alarm, then you might say that "the alarm gets killed". That normally does not happen unless the user uses Force Stop in Settings.However, most likely, the alarm itself is there. However, the device has gone into Doze mode, and so your alarms will be ignored. Your options are:
Try
setAndAllowWhileIdle()
, which may not be sent as frequently as you would like, orHave the user add your app to the battery optimization whitelist, bearing in mind that users may elect to not do this, or
Have the user keep the device plugged in all the time, bearing in mind that users may elect to not do this
Unless you are using a
WakeLock
(carefully), there is a chance that the device will fall back asleep before your service actually gets started.