Search code examples
androidbackgroundtimernotificationsalarmmanager

Running a timer regardless if the activity is active or not


Ive created a timer which counts down and when it reaches 3 it starts vibrating stronger and stronger until at 0 it vibrates fully.

My problem is that if the user turns off the screen the timer becomes unstable, i.e. counting down unpredictably or not at all. After searching around for a while I found that the solution probably is to use the AlarmManager, however this seems very complex for such a simple task.

The timer should be tied to the activity and if set, a notification indicating the time left should also be fired.

Any ideas?


Solution

  • It's clear that timer will be unstable if you implement it in activity. It results from lifecycle of activity. Main activity element it's GUI thread which is not the best place to implements logical elements.

    You should use alarm manager or implement your own service to manage action which will properly work in the background. You have problem because when you switch your screen of your app is paused and until you'll restart it you haven't full control about the action inside activity.

    I'm a fan of programming using brain, so I give advices, not clear code. But I hope that it will help.