AlarmManager 在错误的时间触发警报 [英] AlarmManager fires alarms at wrong time

查看:33
本文介绍了AlarmManager 在错误的时间触发警报的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我管理好一切,创建了一个通知服务,用于根据警报发出通知.不幸的是,使用 AlarmManager 设置警报不起作用.它会在几分钟后触发(不完全是几个小时,这表示时区问题).重复周期为 1 周,因此我使用常量 INTERVAL_DAY 并将其乘以 7.为了确保一个 PendingIntent 不会替换另一个,我将 dayOfWeek 作为第二个参数传递给 PendingIntent.getService().我通过记录来检查警报触发时间的正确性:

I managed everything all right to create a notification service used to fire a notification as a result of an alarm. Unfortunately, setting the alarm using AlarmManager doesn't work right. It fires several minutes later (not exactly hours, which would indicate a timezone problem). The recurring period is 1 week, so I used the constant INTERVAL_DAY and multiplied it with 7. In order to make sure that one PendingIntent doesn't replace the other, I pass the dayOfWeek as second parameter to PendingIntent.getService(). I check the correctness of the time for the alarm to fire by logging it:

Log.d(TAG, "next alarm " + df.format(cal.getTime()));

真的没有办法列出所有设置的警报 - 至少是我自己的应用程序中的警报吗?我相信这是追踪错误的唯一方法.

Is there really no way to list all alarms set - at least those from my own app? I believe this is the only way to track down the error.

我的代码:

cal.setTimeInMillis(System.currentTimeMillis());
cal.add(Calendar.DATE, 1);
cal.set(Calendar.HOUR_OF_DAY, hour);
cal.set(Calendar.MINUTE, minute);
Log.d(TAG, "next alarm " + df.format(cal.getTime()));
Intent showNotificationIntent = new Intent(context, NotificationService.class);
dayOfWeek = cal.get(Calendar.DAY_OF_WEEK);
alarmIntent = PendingIntent.getService(context, dayOfWeek, showNotificationIntent, 0);
getAlarmManager(context).setInexactRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(),
    INTERVAL_WEEK, alarmIntent);

我想提供每天都有一个闹钟,但在不同的时间,可以由用户设置.所以我最多使用 7 个闹钟,应该每周触发一次.

I want to offer to have an alarm every day, but at various times, which can be set by the user. So I use up to 7 alarms, which should fire on a weekly basis.

即使阅读了类似问题的众多答案(我不打算创建重复问题),我也没有找到问题所在.

Even after reading the numerous answers to similar questions (I don't intend to create a duplicate question), I haven't managed to find the problem.

推荐答案

对于低于 19 的 api 级别,您应该使用 AlarmManager.setRepeating() 并且您的警报将在指定时间准确触发.你在 19 级及以上的 api 级别将不再起作用.android 发生了变化,因此所有重复的警报都不准确.因此,如果您想实现精确的重复闹钟,您应该使用 AlarmManager.setExact() 安排闹钟,然后在下周触发闹钟时再次执行,以此类推.

For api levels below 19 you should use AlarmManager.setRepeating() and your alarms will trigger exactly at specified time. Thou on api levels 19 and above this will no longer work. There was change in android so that all repeating alarms are inexact. So if you would like to achieve exact repeating alarm you should schedule alarm with AlarmManager.setExact() and then when alarm triggers do it again for next week and so on every week.

这篇关于AlarmManager 在错误的时间触发警报的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆