Search code examples
androidandroid-widgetalarmmanager

Alarmmanager - Fire alarm on top of every minute


I am trying to fire an Alarm on top of every minute. But as for some reason it doesn't want to work. It is for an Widget Clock which should update every minute. For battery reasons i've made an reciever for screen off and on. So my Alarm only fires when the screen is on. The minutes should be syncron with my System clock.

        public static void startClockTickAlarm() {
            AlarmManager alarmManager = (AlarmManager)_context.getSystemService(Context.ALARM_SERVICE);             
            Calendar calendar = Calendar.getInstance();
            calendar.setTimeInMillis(System.currentTimeMillis());
            calendar.add(Calendar.SECOND, 1);       
            calendar.add(Calendar.HOUR, 1);
            alarmManager.setRepeating(AlarmManager.RTC, utcMillisNextMin(), 60000, createClockTickIntent(_context));
        }

        public static final long utcMillisNextMin() {
            Time t = new Time();
            t.setToNow();
            t.second = 0;
            t.minute++;
            System.out.println("Next Alarm: " + t.hour + ":" + t.minute + ":" + t.second);
            return t.normalize(true);
        }

My System.out gives me exactly what it should. For example i enable my widget at 11:30:15 the returning result is 11:31:00 - This means my alarm should firstly fire at 11:31. According to my System Clock, the alarm is 5-15 seconds too late. The seconds which the alarm fires too late are not always the same (between 5 and 15 seconds).

Thanks in advance.


Solution

  • Like @mighter said, API >= 19 if you must use exact timing, use the setExact() API.

    if(android.os.Build.VERSION.SDK_INT < 19) {
        alarmManager.setRepeating(AlarmManager.RTC, utcMillisNextMin(), 60000, createClockTickIntent(_context));
    } else {
        alarmManager.setExact(...);
    }