I built app that do polling to the server via HTTP requests every 2 seconds, and now I want to make it work even in the background when the screen is black (user press on lock screen button) because when its **minimized **its work. I testing the app on Samsung and I **TURNOFF **the battery optimization for the app and added the app to "never sleeping apps" list via phone settings, and still I not able to make the polling if the phone in lock screen.
I develop medical emergency app and I need to work always, I tried to add FOREGROUND SERVICE its solve the case when the app in the background(minimized) but not when the app in lock screen with black screen.
So my question is there any way to make polling to the server every 2 seconds even if the app in the background(lock screen), I want that the app will continue to work in any case.
I found soultion that work even in DOZE (lock screen) mode, Foreground Service does not guarantee background work, Foreground Service take care of Process Death in Android - that was not my case.
The solution is to use Alarm Manager with setAlarmClock, Foreground Service not required.
private fun setAlarmClock() {
val intent = Intent(requireContext(), AlarmReceiver::class.java)
alarmIntent = PendingIntent.getBroadcast(requireContext(), 0, intent, PendingIntent.FLAG_IMMUTABLE)
val intervalMillis = 5000L
val alarmClockInfo = AlarmManager.AlarmClockInfo(System.currentTimeMillis() + intervalMillis, alarmIntent)
alarmManager.setAlarmClock(alarmClockInfo, alarmIntent)
}