Reading all of today's events using CalendarContract - Android 4.0+

前端 未结 5 957
日久生厌
日久生厌 2020-12-16 01:04

I\'m trying to use Android\'s new calendar API to read all of today\'s calendar events. I\'m have trouble finding the right selection on the database query to return all of

5条回答
  •  無奈伤痛
    2020-12-16 01:44

    I know this is a bit late, but I had a very similar question and had trouble finding the answer I was looking for. The forced-UTC time zone for all-day events made things tricky. Here's my solution:

        // "allDayStart" is an all-day event today, encoded in the default time zone
        Time allDayStart = new Time();
        allDayStart.timezone=TimeZone.getDefault().toString();
        allDayStart.set(dayStart.monthDay, dayStart.month, dayStart.year);
    
        // 2 time selections for the query: 
            // 1) Between day-start and day-end (not all-day); or
            // 2) Equals today at 0:00:00 (all-day) in the default timezone
        String calSelection = 
            "((" + Calendars.ACCOUNT_NAME + " = ?) " +
                "AND (" + Calendars.OWNER_ACCOUNT + "= ?) " +
                "AND (" +
                    "((" + Events.DTSTART + ">= ?) " +
                    "AND (" + Events.DTSTART + "<= ?) " +
                    "AND (" + Events.ALL_DAY + "= ?) " +
                    ") " +
                "OR ((" + Events.DTSTART + "= ?) " +
                    "AND (" + Events.ALL_DAY + "= ?)" +
                    ")" +
                ")" +
            ")"; 
    
        String[] calSelectionArgs = new String[] {
            accountName, ownerName, 
            dayStartInMillis.toString(), dayEndInMillis.toString(), "0", // during today, not all day
            allDayStartInMillis.toString(), "1" // Started today at default start-time for all-day events (all-day), default time zone
        }; 
    

    The query could be refined to not need 2 parts, but this was good enough for me.

    In case it helps, here's where dayStart and dayEnd came from:

        Time dayStart = new Time();
        dayStart.setToNow();
        dayStart.hour=0;
        dayStart.minute=0;
        dayStart.second=0;
    
        Time dayEnd = new Time();
        dayEnd.set(dayStart);
        dayEnd.hour=dayStart.hour+23;
        dayEnd.minute=dayStart.minute+59;
        dayEnd.second=dayStart.second+59;
    
        Long dayStartInMillis = dayStart.toMillis(false);
        Long dayEndInMillis = dayEnd.toMillis(false) + 999;
        Long allDayStartInMillis = allDayStart.toMillis(false);
    

提交回复
热议问题