AlarmManager fires alarm in the wrong time if timezone is different than GMT(UTC)

1.9k Views Asked by At

I know this question was asked a billion times, and I have really tried to make use of the answers but this just can't seem to work as i expect it to. I'm having trouble setting the alarms via AlarmManager - everything seems to be working fine with UTC ( or GMT -whatever you prefer), but when it comes to other timezones the alarms are not fired at the right time. If i set an alarm at 12:00 if my timezone is (+2) it fires up at 14:00, 2 hrs late.

Here's a snippet:

    //todays date in seconds
    long current  =   (System.currentTimeMillis()/86400000)*86400;
    long time =current + 43200;
    alarmManager.set(AlarmManager.RTC_WAKEUP, time*1000,
                            operationBroadcast);

The time on the device is 6:42 AM Here's what i've found in the alarmmanagers "dump" file

RTC_WAKEUP #10: Alarm{420f49b8 type 0 com.pocketenergy.androidbeta}
    type=0 when=+7h17m37s418ms repeatInterval=0 count=0
    operation=PendingIntent{420f3b20: PendingIntentRecord{420f4808 com.pocketenergy.androidbeta broadcastIntent}}

As far as i've read on several places the time should be set in UTC whatever timezone is selected on the actual device, but i have tried a lot of different stuff with the Calendar, for example:

    //todays date in seconds
    long current  =   (System.currentTimeMillis()/86400000)*86400;
    long time =current + 43200;
    Calendar calendar = Calendar.getInstance();
    calendar.setTimeInMillis(time*1000);
    TimeZone timeZone= TimeZone.getTimeZone("UTC"); //also tried TimeZone.getDefault();
    calendar.setTimeZone(timeZone);
    time = cal.getTimeInMillis();
    alarmManager.set(AlarmManager.RTC_WAKEUP, time,
                            operationBroadcast);

Same outcome. Ideas, anybody? :)

1

There are 1 best solutions below

1
On BEST ANSWER

So, I finally got this to work. Here's the code :)

        Calendar calendar = Calendar.getInstance();
        calendar.setTimeInMillis(System.currentTimeMillis());
        calendar.set(Calendar.HOUR_OF_DAY, 12);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
        alarmManager.set(AlarmManager.RTC_WAKEUP, time, operationBroadcast);