
It turns out I was using SystemClock.uptimeMillis() when I should have been using SystemClock.elapsedRealtime(). In addition, it's deceptively simple, always a good sign. It doesn't yet address the clock drift associated with the time spent in calculations during the postDelayed() processing, but it is a step forward. I've got a partial solution to my original post above.
#Deep work timer code#
I'm hoping that this approach will result in a reasonable balance between power conservation, code complexity, and user expectations. The idea is that AlarmManager will help combat clock-drift and PartialWakeLock to help keep the code simple (fingers-crossed). I'm going to try a combination of AlarmManager and PartialWakeLock. Using PartialWakeLock also looks promising, but by itself it doesn't address the clock-drift problem I'm experiencing. AlarmManager seems like a good approach, but I'm concerned that this isn't an appropriate use of AlarmManager (i.e., very short intervals between alarms). Java timers, like services, don't solve the problem with the device going to sleep. Services by themselves won't solve the problem associated with the device going to sleep. The actual numbers are still accurate, but instead of being aligned, for example, on 5 second boundaries which are easily understood by users - the timers involved start to drift, resulting in some understandable user confusion.Īfter a bit of research I found techiques for using services, java timers, AlarmManager, and PartialWakeLock to implement timers. In addition, the postDelayed() approach is experiencing some clock drift, apparently a result of the time spent in the run() method. But I soon learned that it was possible to circumvent this approach by pressing the power button to manually put the device to sleep. My first attempt at this involved using Handler.postDelayed() to trigger the clock ticks every 200ms and _KEEP_SCREEN_ON to ensure that the "clock" wasn't stopped by a screen timeout. The game clock needs to continue to run even if the user explicitly places the device in sleep mode by pressing the power button. Elapsed time needs to be accurate to the second. I'm writing a sports app that needs to track the elapsed time of quarter/half/period.
