简体   繁体   中英

Android Calendar DAY_OF_WEEK returned '1' for monday… but only once?

I have an app that uses alarms to start radio streams. It has a 'repeat daily' function. To check if the alarm should fire on a particular day I check if 'DAY_OF_WEEK' is in an array. Something like this:

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 */ }

(Note: above code may not be 100% java, I've simplified stuff)

This morning, when my code ran, it said dayOfWeek was '0' (Sunday) but it's Monday! And when I set another alarm it suddenly said dayOfWeek was '1'.

Wth? How can this happen?

// UPDATE: Here's the actual code:

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

Looks like it's my own fault. A couple of lines before the code I pasted I set the calendar's time:

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

But I had some weird code that, in certain conditions, caused timeInMs to be a date in the past.

Changed it to

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

that should fix it :P

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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