Search code examples
androidtimeralarmmanager

Best way to do a background timer


Im trying to make a simple game. The game is going great only I want to use a background timer. Like in citybuild games, a task takes x hours to complete and after that there should be a notification. What is the best way to do this? Do I need a background service, an alarmmanager, both? and is it smart to also keep the start timer of the task in an SQLLite db so if the timer stops he can still see it after it starts in the db?

Basicly what I'm asking is, what is best practive and do you guys have some pointers or better yet, examples/tutorials for me?


Solution

  • I recommend you to use the AlarmManager, it's native, you don't have to implement some background service, it doesn't consume battery, and it's easy to use. Please refer to this tutorial.

    Also, you can save the start time in SharedPreferences (or DB, as you prefer), and when the user re-starts the app, check if the job isn't already completed. This is an extra-step to make sure everything works as expected even if AlarmManager goes wrong