Search code examples
androidalarmmanager

AlarmManager - When to setRepeating and how to get time remaining


I have an app which will give the user a bonus power up every 45 minutes. I managed to set a repeating alarm to do it but I have some questions:

1 - Where should I call setRepeating() method? - Having in mind that the alarm should be set automatically and NOT by an onClick event, for instance, I find it tricky to know where to set it. Now I am calling it on the onCreate method of my MainMenu activity. The problem is that everytime he user enters the app it is called. I thought about setting a SharedPreference variable to check if I already called it but it doesn't seem the right approach.

2 - How to the display the time left until next power up? - I would like to display to the user how much time is left until the next power up. The problem is that if the user closes the app and open it again I no longer have a reference to the alarm but it is still running. How can I do that?

Any help will be appreciated. Thanks in advance


Solution

  • I'd use shared preferences for both. When you set the alarm, write a shared preference that says when the next alarm is scheduled for. In onCreate, look at the alarm. If its in the future, no need to set it. If its in the past, set it again. The same answer solves problem 2- subtract the current time from the time in the shared preference, and that's the time left. When the alarm goes off, update the shared preference to the next time.