Android日历DAY_OF_WEEK为星期一返回'1'但只有一次?

时间:2015-01-19 06:14:35

标签: java android calendar

我有一个使用闹钟启动无线电流的应用。它具有“每日重复”功能。要检查警报是否应在某一天触发,我会检查“DAY_OF_WEEK”是否在数组中。像这样:

int[] repeatOnDays = [0,1,1,1,1,1,1]; // first nr is sunday, last is saturday
int dayOfWeek = calendar.get(Calendar.DAY_OF_WEEK)-1; // -1 because Sunday==1 but its index in the array is 0
if (repeatOnDays[dayOfWeek]>0) { /* FIRE ALARM TODAY */ }
else { /* DON'T FIRE ALARM TODAY */ }

(注意:上面的代码可能不是100%java,我简化了东西)

今天早上,当我的代码运行时,它说dayOfWeek为'0'(星期日),但它是星期一!当我再次发出警报时,它突然说当天就是'1'。

WTH?怎么会发生这种情况?

//更新:这是实际代码:

JSONArray repeatDaily = new JSONArray("[0,1,1,1,1,1,1]"); // <- This is not actually here but it may help read the rest of the code :)

boolean fireToday = true;
if (repeat.equals("daily")) {
    Log.d(APPTAG," > Daily repeat..");
    int dayOfWeek = cal.get(Calendar.DAY_OF_WEEK)-1;
    if (repeatDaily.length()<dayOfWeek) { fireToday = false; }
    else if (repeatDaily.getInt(dayOfWeek)>0) { fireToday = true; }
    else { fireToday = false; }
    Log.d(APPTAG," > Day: "+ dayOfWeek +", "+ repeatDaily.getInt(dayOfWeek));
}
if (!fireToday) { 
    Log.d(APPTAG," > Do not need to fire today");
    return; // <-- important stuff
}

logcat的:

06:30:01    D/AlarmMgr  > Daily repeat..
06:30:01    D/AlarmMgr  > Day: 0, 0
06:30:01    D/AlarmMgr  > Do not need to fire today

1 个答案:

答案 0 :(得分:0)

看起来这是我自己的错。在粘贴代码之前的几行我设置了日历的时间:

Calendar cal = Calendar.getInstance();
cal.setTimeInMillis(timeInMs);

但我有一些奇怪的代码,在某些条件下,导致timeInMs成为过去的日期。

将其更改为

Calendar cal = Calendar.getInstance();
cal.setTimeInMillis(System.currentTimeMillis());

应该解决它:P