I was looking at setRepeating(@AlarmType int type, long triggerAtMillis, long intervalMillis, PendingIntent operation)
method of AlarmManager and want to solve a use case.
Use case is I want to set repeating alarms with different intervalMillis
values. Like I want to show a notification after 2 hours, 5 hours and at 9AM the next day. Or I want to do something at every 1st date of month.
I have two solutions to this. Either I set all alarms at once or set the next alarm when previous alarm is received(in case no of alarms are more like with the second use case). Problem is if alarm is missed to be triggerred, I won't be able to trigger further alarms and the whole chain would break.
Is there anything provided by Android for this if I've missed it or else shouldn't Android provide such flexibility?
There are a lot of ways to achieve this. Anyway, all of them need one mutual thing - database. It's clearly easy to understand, you need database to store informations like:
- is alarm valid (e.g or should be turned off, like in Clock app)
- when it should be fired (e.g you restart device and start service viaonBootReceived
and it needs to check if it has to schedule new alarms or not)
Now a little talk about PendingIntent
If you schedule an alarm with the same PendingIntent
- what I mean, intent, data passed in, request code and action are the same, every old alarm after setting up a new one will be overriden and canceled. To avoid that you must pass uri to every alarm you create. Uri
you can simply take from database.
Example:
You want to schedule an alarm that fires PendingIntent
at 5 PM, 8 PM and next day at 10 AM. Let's assume you decide to use setRepeating()
Instead of setting alarms 3 times with setExactAndAllowWhileIdle()
. What you must do is to pass in database those 3 specified times and its calendar days, set interval to fire every 3h and every time alarm fires it has to check in database if it is the time to fire an alarm or not. In this behaviour you will produce more wake-locks (cause every 3h), but you will be ensure that your alarm will be fired.
Maybe I didn't describe it very clearly, but I hope you will understand. I'll also provide some links where I described how to set those alarms and how AlarmManagers
sees PendingIntent
s.:
Scheduling a task to run every 24 hours
Editing scheduled pending intends
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With