所以我正在为 Android 创建闹钟应用程序,但我在设置闹钟时遇到了一些问题。如果今天是星期六,我设置了今天和明天17:15的闹钟,它应该响两次,但它根本不响。此外,如果没有选择任何一天,闹钟将在下次时钟匹配时响起,然后关闭。我在这里搜索了这个问题并找到了很多解决方案,但似乎没有一个对我有用。这是 AlarmReceiver 代码。
public void setAlarmSpecificDay(int dayOfWeek, AlarmManager am, PendingIntent pi, Date time) {
Calendar cal1 = Calendar.getInstance();
int today = cal1.get(Calendar.DAY_OF_WEEK);
int numberOfDaysToAdd = dayOfWeek - today;
if (dayOfWeek < today) {
// Desired day is earlier in the week than today, add 7 days to
// ensure it is in the future
numberOfDaysToAdd += 7;
}
cal1.setTime(time);
cal1.set(Calendar.DAY_OF_WEEK, numberOfDaysToAdd);
Long alarmTime = cal1.getTimeInMillis();
am.setRepeating(AlarmManager.RTC_WAKEUP, alarmTime,( 7 * 24 * 60 * 60 * 1000), pi);
Log.d("Alarm Service", "Alarm set for day " + dayOfWeek + " at ms: " + alarmTime +" " + cal1 );
}
如果我使用此代码并将闹钟设置为在周五、周六和周日响铃,最后的日志将显示:
然后大约 1 分钟后闹钟响了。这一定与我从日历中获取时间的方式有关,但我就是想不通。一直在这里并在谷歌上搜索了几个小时。
Alarm set for day 5 at ms: 1466789400000
Alarm set for day 6 at ms: 1466875800000
Alarm set for day 7 at ms: 1466357400000
这是当我将时钟设置为 19:30 FSS 而现在时钟是 19:38 时应该触发警报的 MS,如果我将 MS 转换为网站上的日期,数字是正确的!
1466789400000 = Fri Jun 24 2016 19:30:00 GMT+0200
1466875800000 = Sat Jun 25 2016 19:30:00 GMT+0200
1466357400000 = Sun Jun 19 2016 19:30:00 GMT+0200
最佳答案
您的代码中有两个问题:
- Pending Intent 被覆盖。因此,只设置了一个警报,因为您正在通过 (FLAG_UPDATE_CURRENT) 更新当前设置的待定 Intent 。
- 在警报管理器中设置了错误的时间。如果您检查第 7 天警报的时间戳,您会发现它已经过去了。因此警报立即触发。
解决方案:
使用唯一的请求代码来创建不同的待定 Intent 。
PendingIntent getBroadcast (上下文上下文, int requestCode,//使用它,设置一些唯一的值 Intent Intent , int 标志)
如果所需的日期早于今天,则将 DAY_OF_YEAR(而不是星期几)加 7 天。
cal1.add(Calendar.DAY_OF_YEAR, numberOfDaysToAdd);
关于java - 设置闹钟以在不同时间重复工作日,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37897929/