Search code examples
androidtimezonealarmmanagergmt

Setting Alarm on 9 AM GMT


I'm having a strange problem. I need to set a task to run exactly at 9 AM GMT. Here's the code I'm using:

AlarmManager mgr = (AlarmManager) context
            .getSystemService(Context.ALARM_SERVICE);
Calendar calendar = Calendar.getInstance(TimeZone
                    .getTimeZone("GMT"));
            calendar.setTimeInMillis(System.currentTimeMillis());
            calendar.set(Calendar.HOUR, 9);
            calendar.set(Calendar.MINUTE, 0);

            mgr.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pi);

My timezone is GMT+2. As a test I've tried to set alarm at this time:

Alarm time = My time - 2 hours + couple of minutes to catch the alarm

But it never worked. Am I missing something? Thanks in advance.


Solution

  • This could be the problem:

    calendar.set(Calendar.HOUR, 9);
    

    That's setting the "hour of the morning or afternoon" - do if you're already in the afternoon, it'll set it to 9pm. I think you want:

    calendar.set(Calendar.HOUR_OF_DAY, 9);
    

    It's possible that that doesn't explain your problem, but it's certainly one thing to fix. Note that it will be on the same day - so if you do this after 9am, it's not going to fire.

    (You should probably set the seconds field to 0, too.)