简体   繁体   English

Alarmmanager-每分钟的顶部都有火灾警报

[英]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. 我的System.out给了我确切的信息。 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. 例如,我在11:30:15启用我的窗口小部件,返回结果是11:31:00-这意味着我的闹钟应首先在11:31触发。 According to my System Clock, the alarm is 5-15 seconds too late. 根据我的系统时钟,闹钟晚了5-15秒。 The seconds which the alarm fires too late are not always the same (between 5 and 15 seconds). 警报触发时间太晚的秒数不一定总是相同(5到15秒之间)。

Thanks in advance. 提前致谢。

Like @mighter said, API >= 19 if you must use exact timing, use the setExact() API. 就像@mighter所说的那样,API> = 19,如果必须使用精确的计时,请使用setExact() API。

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

There's following statement in docs : docs中有以下声明:

Note: as of API 19, all repeating alarms are inexact. 注意:从API 19开始,所有重复警报都是不精确的。 If your application needs precise delivery times then it must use one-time exact alarms, rescheduling each time as described above. 如果您的应用程序需要精确的交付时间,则它必须使用一次性精确警报,并如上所述每次重新安排。 Legacy applications whose targetSdkVersion is earlier than API 19 will continue to have all of their alarms, including repeating alarms, treated as exact. targetSdkVersion早于API 19的旧版应用程序将继续将其所有警报(包括重复警报)视为精确警报。

If you're running on Android 4.4.4 then this might be the reason. 如果您在Android 4.4.4上运行,则可能是原因。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM