'Kotlin: CountDownTimer stops running in service when screen is off

I have a service running even when screen is off. That works well when listening to a ble-device or a firebase database. But i have a problem with a simple CountdownTimer. The CountdownTimer obviously pauses when the screen is off while all the other listeners to firebase and the ble-device are still listening. The timer continues running as soon as screen is on again, but then the timing is obviosuly delayed for the time the screen was off. What could be the problem here? Is the timer running in an extra thread which pauses because it is somehow not part of the service?

When my phone is connected to the pc/AndroidStudio the timer continues running as expected. But when not connected to the pc it pauses as soon as screen is off.

Btw: I'm using Android 8, i tried it also on android 12 but on that version my whole application is reset when screen is off and also the service doesn't run anymore. Meaybe that gives a hint... Anyway, im fine running it on Android 8.

private fun activate(){
        nextEvent = refreshNextEvent()
        onNewTimerEventSchedule?.invoke(this.timerDefinition.id!!,nextEvent)
        if (nextEvent!=null){
            val interval =  LocalDateTime.now().until(nextEvent!!.time, ChronoUnit.MILLIS)
            timer = object: CountDownTimer(interval, interval) {
                override fun onTick(millisUntilFinished: Long) {}
                override fun onFinish() {
                    onTimer?.invoke(nextEvent!!.commandInt)
                    activate()
                    this.cancel()
                }
            }
            timer!!.start()
        }
    }

In the meanwhile I even added a wakelock (partial, and also tried full), but still no effect... Wake lock was done in this way: Partial wake lock is not working



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source