Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to prevent alarm from running the passed time on starting

I have an application with a RTC alarm. Currently I set the alarm to fire daily at 8:00AM. My problem is that when the alarm starts say at (4:00PM), it will consider the starting time (8AM) already in the past and hence will run.

I want the alarm to run only around 8:00AM, but if it is started late in the day, doesn't run. Any idea how?

like image 380
Mahmoud Badri Avatar asked Dec 21 '25 15:12

Mahmoud Badri


2 Answers

I suggest you to use to calendar.add(Calendar.DAY_OF_YEAR, 1);

Study following code:

Calendar calendar = Calendar.getInstance();
// 9 AM 
calendar.add(Calendar.DAY_OF_YEAR, 1);   ///to avoid firing the alarm immediately
calendar.set(Calendar.HOUR_OF_DAY, 9);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);
PendingIntent pi = PendingIntent.getService(context, 0,
            new Intent(context, MyClass.class),PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
am.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(),
                                AlarmManager.INTERVAL_DAY, pi);

Original Source

like image 177
Lucifer Avatar answered Dec 24 '25 05:12

Lucifer


You are using setInexactRepeating or setRepeating, right? So to handle such situations just compare 2 times: current time in msecs and (8AM, current day) in msecs. If first time more than the second one, then you should trigger your alarm on (8AM, next day), if not - (8AM, current day).

like image 25
nikis Avatar answered Dec 24 '25 05:12

nikis



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!