0

My app will set an AlarmManager to fire some event and repeat it on 12:00pm everyday. However, my clients report that the alarm sometimes wake up normally, but sometimes wake up at other time (eg. 10/11pm).

Here is the code snippet:

Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
if (calendar.get(Calendar.HOUR_OF_DAY) >= 12 && calendar.get(Calendar.MINUTE) > 0)  {
    calendar.add(Calendar.DAY_OF_MONTH, 1);
}
calendar.set(Calendar.HOUR, 0);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);
calendar.set(Calendar.AM_PM, Calendar.PM);
int interval = (60 * 60 * 24 * 1000);

Intent intent = new Intent(mContext, AlarmReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(mContext, AlarmReceiver.REQUEST_CODE, intent, PendingIntent.FLAG_UPDATE_CURRENT);

AlarmManager alarmManager = (AlarmManager)mContext.getSystemService(Context.ALARM_SERVICE);
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), interval, pendingIntent);

For cancelling the alarm:

Intent intent = new Intent(mContext, AlarmReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(mContext, AlarmReceiver.REQUEST_CODE, intent, PendingIntent.FLAG_UPDATE_CURRENT);

AlarmManager alarmManager = (AlarmManager)mContext.getSystemService(Context.ALARM_SERVICE);
alarmManager.cancel(pendingIntent);

My app will start the alarm when the app is launch/turn on this setting in one of the activity. Therefore I use the FLAG_UPDATE_CURRENT to ensure only one task will fire at the specific time. Is there something missing in my code that result in firing the alarm at a wrong time?

Hanon
  • 3,917
  • 2
  • 25
  • 29

1 Answers1

0

I think you could do this in simpler way like below:

Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.set(Calendar.HOUR_OF_DAY, 12);  // 12 PM

alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(),
        60 * 60 * 24 * 1000, pendingIntent); // Daily interval, setting RTC_WAKEUP does exact time and forces device to wake up.

Hope this helps.

bond
  • 11,236
  • 7
  • 48
  • 62