Ошибка при добавлении повторяющегося события в Календаре

Привет, я пытаюсь создать приложение, которое добавляет события в календарь. Например, мне нужно создать событие каждую субботу до 31 декабря. Ниже приведены атрибуты, которые я установил для создания событий.

event.put(CalendarContract.Events.CALENDAR_ID, 1);
        event.put(CalendarContract.Events.TITLE, title);
        event.put(CalendarContract.Events.DESCRIPTION, description);
        event.put(CalendarContract.Events.EVENT_LOCATION, location);
        event.put(CalendarContract.Events.DTSTART, sDate);
        event.put(CalendarContract.Events.DURATION,"P50S");
        event.put(CalendarContract.Events.ALL_DAY, 0);
        event.put(CalendarContract.Events.HAS_ALARM, hasAlarm);
        event.put(CalendarContract.Events.EVENT_TIMEZONE, timeZone);
event.put(CalendarContract.Events.RRULE, "FREQ=WEEKLY;BYDAY=SA;UNTIL=20151230");
mContext.getContentResolver().insert(baseUri, event);

Но он создает событие на заданную дату (sDate), а затем создает каждую субботу. Но как я могу избежать этого одного события, созданного в заданную дату (sDate)


person ranjith    schedule 09.11.2015    source источник


Ответы (1)


У меня такая же проблема. Вам необходимо проверить правило повторения для дня недели и сместить DTSTART на ближайшую субботу (или любой другой день недели, указанный в правиле повторения). Чтобы дать вам грубый пример, как это сделать, я прикрепляю код из приложения Android Calendar, который смещает время начала и время окончания события на основе строки правила повторения и возвращает два длинных значения — новое время начала и новое время окончания, если смещение было применено или null, если это не так. Класс EventRecurrence можно найти с помощью поиска в GrepCode, его части приложения календаря Android.

public static long[] offsetStartTimeIfNecessary(long startMilis, long endMilis, String rrule) {
    if (rrule == null || rrule.isEmpty() || rrule.replace("RRULE:", "").isEmpty()) {
        // No need to waste any time with the parsing if the rule is empty.
        return null;
    }
    long result[] = new long[2];
    Calendar startTime = Calendar.getInstance();
    startTime.setTimeInMillis(startMilis);
    Calendar endTime = Calendar.getInstance();
    endTime.setTimeInMillis(endMilis);
    EventRecurrence mEventRecurrence = new EventRecurrence();
    mEventRecurrence.parse(rrule.replace("RRULE:", ""));
    // Check if we meet the specific special case. It has to:
    //  * be weekly
    //  * not recur on the same day of the week that the startTime falls on
    // In this case, we'll need to push the start time to fall on the first day of the week
    // that is part of the recurrence.
    if (mEventRecurrence.freq != EventRecurrence.WEEKLY) {
        // Not weekly so nothing to worry about.
        return null;
    }
    if (mEventRecurrence.byday == null ||
            mEventRecurrence.byday.length > mEventRecurrence.bydayCount) {
        // This shouldn't happen, but just in case something is weird about the recurrence.
        return null;
    }
    // Start to figure out what the nearest weekday is.
    int closestWeekday = Integer.MAX_VALUE;
    int weekstart = EventRecurrence.day2TimeDay(mEventRecurrence.wkst);
    int startDay = startTime.get(Calendar.DAY_OF_WEEK) - 1;
    for (int i = 0; i < mEventRecurrence.bydayCount; i++) {
        int day = EventRecurrence.day2TimeDay(mEventRecurrence.byday[i]);
        if (day == startDay) {
            // Our start day is one of the recurring days, so we're good.
            return null;
        }
        if (day < weekstart) {
            // Let's not make any assumptions about what weekstart can be.
            day += 7;
        }
        // We either want the earliest day that is later in the week than startDay ...
        if (day > startDay && (day < closestWeekday || closestWeekday < startDay)) {
            closestWeekday = day;
        }
        // ... or if there are no days later than startDay, we want the earliest day that is
        // earlier in the week than startDay.
        if (closestWeekday == Integer.MAX_VALUE || closestWeekday < startDay) {
            // We haven't found a day that's later in the week than startDay yet.
            if (day < closestWeekday) {
                closestWeekday = day;
            }
        }
    }
    if (closestWeekday < startDay) {
        closestWeekday += 7;
    }
    int daysOffset = closestWeekday - startDay;
    startTime.add(Calendar.DAY_OF_MONTH, daysOffset);
    endTime.add(Calendar.DAY_OF_MONTH, daysOffset);
    result[0] = startTime.getTimeInMillis();
    result[1] = endTime.getTimeInMillis();
    return result;
}
person qbasso    schedule 17.11.2015