/** * Make a WHERE clause to filter selected calendars * @return generated WHERE clause, or en empty string if there is no calendar selected */ private String getEventCalendarIdsSelectString() { LinkedHashMap<Long, Boolean> checkedCalendars = PreferencesManager.getCheckedCalendars(context); StringBuilder builder = new StringBuilder(); boolean first = true; for(long idCalendar : checkedCalendars.keySet()) { if(first) first = false; else builder.append(" OR "); builder.append("(").append(Instances.CALENDAR_ID).append("=").append(idCalendar).append(")"); } return builder.toString(); }
protected Uri getContentUri(int numberOfDaysFromNow) { Calendar beginTime = Calendar.getInstance(); beginTime.add(Calendar.DAY_OF_MONTH, -1); beginTime.set(Calendar.HOUR_OF_DAY, 23); beginTime.set(Calendar.MINUTE, 59); long startMillis = beginTime.getTimeInMillis(); Calendar endTime = Calendar.getInstance(); endTime.set(Calendar.HOUR_OF_DAY, 23); endTime.set(Calendar.MINUTE, 59); endTime.add(Calendar.DAY_OF_MONTH, numberOfDaysFromNow-1); long endMillis = endTime.getTimeInMillis(); // Construct the query with the desired date range. Uri.Builder builder = Instances.CONTENT_URI.buildUpon(); ContentUris.appendId(builder, startMillis); ContentUris.appendId(builder, endMillis); return builder.build(); }
/** * Performs a query to return all visible instances in the given range * that match the given selection. This is a blocking function and * should not be done on the UI thread. This will cause an expansion of * recurring events to fill this time range if they are not already * expanded and will slow down for larger time ranges with many * recurring events. * * @param cr The ContentResolver to use for the query * @param projection The columns to return * @param begin The start of the time range to query in UTC millis since * epoch * @param end The end of the time range to query in UTC millis since * epoch * @param selection Filter on the query as an SQL WHERE statement * @param selectionArgs Args to replace any '?'s in the selection * @param orderBy How to order the rows as an SQL ORDER BY statement * @return A Cursor of instances matching the selection */ private static final Cursor instancesQuery(ContentResolver cr, String[] projection, int startDay, int endDay, String selection, String[] selectionArgs, String orderBy) { String WHERE_CALENDARS_SELECTED = Calendars.VISIBLE + "=?"; String[] WHERE_CALENDARS_ARGS = {"1"}; String DEFAULT_SORT_ORDER = "begin ASC"; Uri.Builder builder = Instances.CONTENT_BY_DAY_URI.buildUpon(); ContentUris.appendId(builder, startDay); ContentUris.appendId(builder, endDay); if (TextUtils.isEmpty(selection)) { selection = WHERE_CALENDARS_SELECTED; selectionArgs = WHERE_CALENDARS_ARGS; } else { selection = "(" + selection + ") AND " + WHERE_CALENDARS_SELECTED; if (selectionArgs != null && selectionArgs.length > 0) { selectionArgs = Arrays.copyOf(selectionArgs, selectionArgs.length + 1); selectionArgs[selectionArgs.length - 1] = WHERE_CALENDARS_ARGS[0]; } else { selectionArgs = WHERE_CALENDARS_ARGS; } } return cr.query(builder.build(), projection, selection, selectionArgs, orderBy == null ? DEFAULT_SORT_ORDER : orderBy); }
/** * Updates the uri used by the loader according to the current position of * the listview. * * @return The new Uri to use */ private Uri updateUri() { SimpleWeekView child = (SimpleWeekView) mListView.getChildAt(0); if (child != null) { int julianDay = child.getFirstJulianDay(); mFirstLoadedJulianDay = julianDay; } // -1 to ensure we get all day events from any time zone mTempTime.setJulianDay(mFirstLoadedJulianDay - 1); long start = mTempTime.toMillis(true); mLastLoadedJulianDay = mFirstLoadedJulianDay + (mNumWeeks + 2 * WEEKS_BUFFER) * 7; // +1 to ensure we get all day events from any time zone mTempTime.setJulianDay(mLastLoadedJulianDay + 1); long end = mTempTime.toMillis(true); // Create a new uri with the updated times Uri.Builder builder = Instances.CONTENT_URI.buildUpon(); ContentUris.appendId(builder, start); ContentUris.appendId(builder, end); return builder.build(); }
@Override protected EnumMap<KeyIndex, String> initContentProviderKeys() { EnumMap<KeyIndex, String> keys = new EnumMap<KeyIndex, String>( KeyIndex.class); keys.put(KeyIndex.CALENDARS_ID, Calendars._ID); keys.put(KeyIndex.CALENDARS_NAME, Calendars.NAME); keys.put(KeyIndex.CALENDARS_DISPLAY_NAME, Calendars.CALENDAR_DISPLAY_NAME); keys.put(KeyIndex.CALENDARS_VISIBLE, Calendars.VISIBLE); keys.put(KeyIndex.EVENTS_ID, Events._ID); keys.put(KeyIndex.EVENTS_CALENDAR_ID, Events.CALENDAR_ID); keys.put(KeyIndex.EVENTS_DESCRIPTION, Events.DESCRIPTION); keys.put(KeyIndex.EVENTS_LOCATION, Events.EVENT_LOCATION); keys.put(KeyIndex.EVENTS_SUMMARY, Events.TITLE); keys.put(KeyIndex.EVENTS_START, Events.DTSTART); keys.put(KeyIndex.EVENTS_END, Events.DTEND); keys.put(KeyIndex.EVENTS_RRULE, Events.RRULE); keys.put(KeyIndex.EVENTS_ALL_DAY, Events.ALL_DAY); keys.put(KeyIndex.INSTANCES_ID, Instances._ID); keys.put(KeyIndex.INSTANCES_EVENT_ID, Instances.EVENT_ID); keys.put(KeyIndex.INSTANCES_BEGIN, Instances.BEGIN); keys.put(KeyIndex.INSTANCES_END, Instances.END); keys.put(KeyIndex.ATTENDEES_ID, Attendees._ID); keys.put(KeyIndex.ATTENDEES_EVENT_ID, Attendees.EVENT_ID); keys.put(KeyIndex.ATTENDEES_NAME, Attendees.ATTENDEE_NAME); keys.put(KeyIndex.ATTENDEES_EMAIL, Attendees.ATTENDEE_EMAIL); keys.put(KeyIndex.ATTENDEES_STATUS, Attendees.ATTENDEE_STATUS); return keys; }
@Override protected Cursor queryEventInstances(long startFrom, long startTo, String[] projection, String selection, String[] selectionArgs, String sortOrder) { Uri.Builder builder = Instances.CONTENT_URI.buildUpon(); ContentUris.appendId(builder, startFrom); ContentUris.appendId(builder, startTo); return this.cordova.getActivity().getContentResolver().query( builder.build(), projection, selection, selectionArgs, sortOrder); }
@Override protected EnumMap<KeyIndex, String> initContentProviderKeys() { EnumMap<KeyIndex, String> keys = new EnumMap<KeyIndex, String>( KeyIndex.class); keys.put(KeyIndex.CALENDARS_ID, Calendars._ID); keys.put(KeyIndex.CALENDARS_NAME, Calendars.NAME); keys.put(KeyIndex.CALENDARS_VISIBLE, Calendars.VISIBLE); keys.put(KeyIndex.EVENTS_ID, Events._ID); keys.put(KeyIndex.EVENTS_CALENDAR_ID, Events.CALENDAR_ID); keys.put(KeyIndex.EVENTS_DESCRIPTION, Events.DESCRIPTION); keys.put(KeyIndex.EVENTS_LOCATION, Events.EVENT_LOCATION); keys.put(KeyIndex.EVENTS_SUMMARY, Events.TITLE); keys.put(KeyIndex.EVENTS_START, Events.DTSTART); keys.put(KeyIndex.EVENTS_END, Events.DTEND); keys.put(KeyIndex.EVENTS_RRULE, Events.RRULE); keys.put(KeyIndex.EVENTS_ALL_DAY, Events.ALL_DAY); keys.put(KeyIndex.INSTANCES_ID, Instances._ID); keys.put(KeyIndex.INSTANCES_EVENT_ID, Instances.EVENT_ID); keys.put(KeyIndex.INSTANCES_BEGIN, Instances.BEGIN); keys.put(KeyIndex.INSTANCES_END, Instances.END); keys.put(KeyIndex.ATTENDEES_ID, Attendees._ID); keys.put(KeyIndex.ATTENDEES_EVENT_ID, Attendees.EVENT_ID); keys.put(KeyIndex.ATTENDEES_NAME, Attendees.ATTENDEE_NAME); keys.put(KeyIndex.ATTENDEES_EMAIL, Attendees.ATTENDEE_EMAIL); keys.put(KeyIndex.ATTENDEES_STATUS, Attendees.ATTENDEE_STATUS); return keys; }
private boolean fetchSystemEvents(Context mContext) { Calendar cal = GregorianCalendar.getInstance(); Long dtStart = cal.getTime().getTime(); cal.add(Calendar.DATE, lookahead_days); Long dtEnd = cal.getTime().getTime(); Uri.Builder eventsUriBuilder = CalendarContract.Instances.CONTENT_URI.buildUpon(); ContentUris.appendId(eventsUriBuilder, dtStart); ContentUris.appendId(eventsUriBuilder, dtEnd); Uri eventsUri = eventsUriBuilder.build(); try (Cursor evtCursor = mContext.getContentResolver().query(eventsUri, EVENT_INSTANCE_PROJECTION, null, null, CalendarContract.Instances.BEGIN + " ASC")) { if (evtCursor == null || evtCursor.getCount() == 0) { return false; } while (evtCursor.moveToNext()) { CalendarEvent calEvent = new CalendarEvent( evtCursor.getLong(1), evtCursor.getLong(2), evtCursor.getLong(3), evtCursor.getString(4), evtCursor.getString(5), evtCursor.getString(6), evtCursor.getString(7) ); calendarEventList.add(calEvent); } return true; } }
private void listNextCalenderEvents( ) { ContentResolver cr = this.getContentResolver( ); Cursor cursor = null; // cursor = cr.query( ContactsContract.Contacts.CONTENT_URI, new String[ ] { PhoneLookup.DISPLAY_NAME, // PhoneLookup.PHOTO_URI }, null, null, // null ); long begin = System.currentTimeMillis( ); // starting time in milliseconds long end = begin + ( 1000 * 60 * 60 * 2 ); // ending time in milliseconds String[ ] proj = new String[ ] { Instances._ID, Instances.BEGIN, Instances.END, Instances.EVENT_ID }; cursor = Instances.query( getContentResolver( ), proj, begin, end ); if ( cursor == null ) { Log.d( "CONTACTS", "keine Kontakte gefunden" ); } else { cursor.moveToFirst( ); while ( cursor.isAfterLast( ) == false ) { Log.d( "CONTACTS", cursor.getString( 0 ) + " " + cursor.getString( 1 ) + " " + cursor.getString( 2 ) + " " + cursor.getString( 3 ) ); printEventDetails( Long.parseLong( cursor.getString( 3 ) ) ); cursor.moveToNext( ); } } cursor.close( ); }
private Uri getInstancesQueryUri() { // Event search window : from one month before to one month after, to be sure GregorianCalendar dateDebut = new GregorianCalendar(); dateDebut.add(GregorianCalendar.MONTH, -1); GregorianCalendar dateFin = new GregorianCalendar(); dateFin.add(GregorianCalendar.MONTH, 1); // search URI (contains the search window) Uri.Builder builder = Instances.CONTENT_URI.buildUpon(); ContentUris.appendId(builder, dateDebut.getTimeInMillis()); ContentUris.appendId(builder, dateFin.getTimeInMillis()); return builder.build(); }
/** * Get the next event in the calendars set in the preferences * @param currentTime Time to use to search for events * @param early Delay to extend event start time before the real start time * @return The first event found, or null if there is none */ public CalendarEvent getNextEvent(long currentTime, long early, boolean onlyBusy) { ContentResolver cr = context.getContentResolver(); // Make the calendar ID selection string String calIdsSelect = getEventCalendarIdsSelectString(); if(calIdsSelect.equals("")) return null; // Selection is inclusive on event start time. // This way we are consistent wih getCurrentEvent String selection = "(" + calIdsSelect + ") AND " + Instances.BEGIN + " >= ? AND " + Instances.ALL_DAY + " = 0"; if(onlyBusy) { selection += " AND " + Instances.AVAILABILITY + " = " + Instances.AVAILABILITY_BUSY; } // Substract early from Instances.BEGIN -> same as adding early to currentTime when comparing String strCurrentTime = String.valueOf(currentTime + early); String[] selectionArgs = new String[] { strCurrentTime }; Cursor cur = cr.query(getInstancesQueryUri(), INSTANCE_PROJECTION, selection, selectionArgs, Instances.BEGIN); // Sort by start time to get the first event CalendarEvent res; if(cur != null && cur.moveToNext()) res = new CalendarEvent(cur.getString(INSTANCE_PROJECTION_TITLE_INDEX), cur.getLong(INSTANCE_PROJECTION_BEGIN_INDEX), cur.getLong(INSTANCE_PROJECTION_END_INDEX)); else { res = null; } if(cur != null) { cur.close(); } return res; }
/** * Commodity method to generate the correct filter string and arguments list according to the owners and visibility defined * * @param idCalendars calendar IDs to filter * @param calendarDisplayNames calendar display name to filter * @return a {@code Pair} containing as first field the selection string and as second field the selection arguments */ private static Pair<String, String[]> filterOnCalendarIDAndCalendarDisplayName(Collection<Integer> idCalendars, Collection<String> calendarDisplayNames) { String selection = null; String selectionArgs[] = null; if (idCalendars != null && idCalendars.size() == 0) { idCalendars = null; } if (calendarDisplayNames != null && calendarDisplayNames.size() == 0) { calendarDisplayNames = null; } if (idCalendars != null || calendarDisplayNames != null) { // selection will look like // calendar_id=? OR calendar_id=? OR calendar_displayName=? OR calendar_displayName=? StringBuilder builder = new StringBuilder(); List<String> arguments = new ArrayList<>(); if (idCalendars != null) { for (Integer idCalendar : idCalendars) { builder.append(Instances.CALENDAR_ID).append("=? OR "); arguments.add(idCalendar + ""); } builder.setLength(builder.length() - 4); } if (calendarDisplayNames != null) { for (String calendarDisplayName : calendarDisplayNames) { builder.append(Instances.CALENDAR_DISPLAY_NAME).append("=? OR "); arguments.add(calendarDisplayName); } builder.setLength(builder.length() - 4); } selection = builder.toString(); selectionArgs = arguments.toArray(new String[arguments.size()]); } return Pair.create(selection, selectionArgs); }
private PendingIntent getPendingIntent(Instance instance) { Intent muteIntent = new Intent(getApplicationContext(), MutePhoneBroadcastReceiver.class); muteIntent.setAction(Actions.MUTE); muteIntent.putExtra(Instances.DTEND, instance.getEndDate()); muteIntent.putExtra(Instances._ID, instance.getId()); return PendingIntent.getBroadcast(getApplicationContext(), instance.getId(), muteIntent, PendingIntent.FLAG_CANCEL_CURRENT); }
private String buildQuerySelection() { // Respect the preference to show/hide declined events if (mHideDeclined) { return Calendars.VISIBLE + "=1 AND " + Instances.SELF_ATTENDEE_STATUS + "!=" + Attendees.ATTENDEE_STATUS_DECLINED; } else { return Calendars.VISIBLE + "=1"; } }
private Uri buildQueryUri(int start, int end, String searchQuery) { Uri rootUri = searchQuery == null ? Instances.CONTENT_BY_DAY_URI : Instances.CONTENT_SEARCH_BY_DAY_URI; Uri.Builder builder = rootUri.buildUpon(); ContentUris.appendId(builder, start); ContentUris.appendId(builder, end); if (searchQuery != null) { builder.appendPath(searchQuery); } return builder.build(); }
protected String updateWhere() { // TODO fix selection/selection args after b/3206641 is fixed String where = WHERE_CALENDARS_VISIBLE; if (mHideDeclined || !mShowDetailsInMonth) { where += " AND " + Instances.SELF_ATTENDEE_STATUS + "!=" + Attendees.ATTENDEE_STATUS_DECLINED; } return where; }
/** * @return The uri for the loader */ private Uri createLoaderUri() { long now = System.currentTimeMillis(); // Add a day on either side to catch all-day events long begin = now - DateUtils.DAY_IN_MILLIS; long end = now + SEARCH_DURATION + DateUtils.DAY_IN_MILLIS; Uri uri = Uri.withAppendedPath(Instances.CONTENT_URI, Long.toString(begin) + "/" + end); return uri; }
public startAndEnd nextActionTimes( Context context, long currentTime, int classNum) { int before = PrefsManager.getBeforeMinutes(context, classNum) * 60000; int after = PrefsManager.getAfterMinutes(context, classNum) * 60000; startAndEnd result = new startAndEnd(); long triggerEnd = PrefsManager.getLastTriggerEnd(context, classNum); if (triggerEnd > currentTime) { result.startTime = currentTime; result.endTime = triggerEnd; result.startEventName = "<immediate>"; result.endEventName = "<immediate>"; } else { result.startTime = Long.MAX_VALUE; result.endTime = currentTime; result.startEventName = ""; result.endEventName = ""; } ContentResolver cr = context.getContentResolver(); StringBuilder selClause = selection(context, classNum); selClause.append(" AND ( ").append(Instances.END) .append(" > ? )"); String[] selectionArgs = new String[] { String.valueOf(currentTime - after)}; // Do query sorted by start time Cursor cur = cr.query(getInstancesQueryUri(), INSTANCE_PROJECTION, selClause.toString(), selectionArgs, Instances.BEGIN); while (cur.moveToNext()) { long start = cur.getLong(INSTANCE_PROJECTION_BEGIN_INDEX) - before; long end = cur.getLong(INSTANCE_PROJECTION_END_INDEX) + after; if (start < result.startTime) { // This can only happen once, because we sort the // query on ascending start time result.startTime = start; if (end > result.endTime) { result.endTime = end; result.startEventName = cur.getString(INSTANCE_PROJECTION_TITLE_INDEX); result.endEventName = result.startEventName; } } else if (start <= result.endTime) { // This event starts or started before our current end if (end > result.endTime) { // extend end time for overlapping event result.endTime = end; result.endEventName = cur.getString(INSTANCE_PROJECTION_TITLE_INDEX); } } if (start > currentTime) { // This event starts in the future // We need not consider any later ones, because we will // set an alarm for its start time or earlier and look again break; } } cur.close(); return result; }
/** * Get the current event in one of the calendars set in the preferences * @param currentTime Time at which the event should be searched * @param delay Delay that extends the search interval towards the end * @param early Delay that extends the search interval towards the beginning * @return The first event found, or null if there is none */ public CalendarEvent getCurrentEvent(long currentTime, long delay, long early, boolean onlyBusy) { ContentResolver cr = context.getContentResolver(); // Make the calendar ID selection string String calIdsSelect = getEventCalendarIdsSelectString(); if(calIdsSelect.equals("")) { return null; } int permissionCheck = ContextCompat.checkSelfPermission(context, Manifest.permission.READ_CALENDAR); if(permissionCheck != PackageManager.PERMISSION_GRANTED) { return null; } // Selection must be inclusive on the start time, and eclusive on the end time. // This way when setting an alarm at the end of the event, this moment is considered outside of the event String selection = "(" + calIdsSelect + ") AND " + Instances.BEGIN + " <= ? AND " + Instances.END + " > ? AND " + Instances.ALL_DAY + " = 0"; if(onlyBusy) { selection += " AND " + Instances.AVAILABILITY + " = " + Instances.AVAILABILITY_BUSY; } String strCurrentTimeEarly = String.valueOf(currentTime + early); String strCurrentTimeDelay = String.valueOf(currentTime - delay); String[] selectionArgs = new String[] { strCurrentTimeEarly, strCurrentTimeDelay }; Cursor cur = cr.query(getInstancesQueryUri(), INSTANCE_PROJECTION, selection, selectionArgs, Instances.END); // Take the event that ends first CalendarEvent res; if(cur != null && cur.moveToNext()) { res = new CalendarEvent(cur.getString(INSTANCE_PROJECTION_TITLE_INDEX), cur.getLong(INSTANCE_PROJECTION_BEGIN_INDEX), cur.getLong(INSTANCE_PROJECTION_END_INDEX)); } else { res = null; } if(cur != null) { cur.close(); } return res; }
@Override public void run() { clearAllEvents(); cal = new GregorianCalendar(); Calendar newCal = new GregorianCalendar(); //Reset at 12:30am int hourOfDay = cal.get(Calendar.HOUR_OF_DAY); int minOfDay = cal.get(Calendar.MINUTE); if(hourOfDay == 0 && minOfDay < 30){ newCal.set(Calendar.HOUR_OF_DAY, 0); newCal.set(Calendar.MINUTE, 30); newCal.set(Calendar.SECOND, 0); } else{ newCal.add(Calendar.DAY_OF_WEEK, 1); //recalculates calendar if at the end newCal.set(Calendar.HOUR_OF_DAY, 0); newCal.set(Calendar.MINUTE, 30); newCal.set(Calendar.SECOND, 0); } String[] mSelectionArgs = new String[3]; String mSelection = "DELETED = ? AND hasAlarm = ? AND allDay = ?"; long start = cal.getTimeInMillis(); //current time long stop = newCal.getTimeInMillis(); //end of day mSelectionArgs[0] = "0"; mSelectionArgs[1] = "1"; mSelectionArgs[2] = "0"; Cursor calendar = getContentResolver().query(Events.CONTENT_URI, null, mSelection, mSelectionArgs, Events.DTSTART+" ASC"); //Go through and grab all events with reminders with our time constraint if(calendar != null && calendar.moveToFirst()){ do{ String repeating = calendar.getString(calendar.getColumnIndex("rrule")); long begin = calendar.getLong(calendar.getColumnIndex(Events.DTSTART)); long end = calendar.getLong(calendar.getColumnIndex(Events.DTEND)); if((repeating == null && begin >= start && end <= stop) || (repeating != null)){ String id = calendar.getString(calendar.getColumnIndex(Events._ID)); String name = calendar.getString(calendar.getColumnIndex(Events.TITLE)); //Filter out deleted instances and grab repeating events String[] INSTANCE_PROJECTION = new String[] { Instances.EVENT_ID, // 0 Instances.BEGIN, // 1 Instances.END, // 2 Instances.TITLE // 3 }; String selection = Instances.EVENT_ID + " = ?"; String[] selectionArgs = new String[] {id}; Cursor instances = null; //Uri for events withing start and stop Uri.Builder builder = Instances.CONTENT_URI.buildUpon(); ContentUris.appendId(builder, start); ContentUris.appendId(builder, stop); instances = getContentResolver().query(builder.build(), INSTANCE_PROJECTION, selection, selectionArgs, null); if(instances == null || instances.getCount() > 0 && instances.moveToNext()){ //Make sure the instance's begin is after current time (since we didn't check it before) if(instances.getLong(instances.getColumnIndex((Instances.BEGIN))) >= start){ begin = instances.getLong(instances.getColumnIndex(Instances.BEGIN)); end = instances.getLong(instances.getColumnIndex(Instances.END)); String[] toReturn = {""}; toReturn[0] = ""+id; int maxReminder = 0; Cursor reminders = getContentResolver().query(Reminders.CONTENT_URI, null, "event_id = ?", toReturn, null); if(reminders != null && reminders.moveToLast()){ do{ int rem = reminders.getInt(reminders.getColumnIndex(Reminders.MINUTES)) ; if(rem > maxReminder) maxReminder = rem; }while(reminders.moveToPrevious()); } if(maxReminder >= 1 && maxReminder <= 60){ CalendarEvent e = new CalendarEvent(id,name,begin,end,maxReminder); eventList.add(e); } } } if(instances != null && ! instances.isClosed() ) instances.close(); } }while(calendar.moveToNext()); } if(calendar != null && ! calendar.isClosed() ) calendar.close(); //Run this again when you reach 12:30am either today or the next day long current = System.currentTimeMillis(); if(eventList.size() > 0) startCalendarAlarm(0); thread_calSetup.postDelayed(this, (stop-current)); }
/** * Extract an EventInfo object from its representation as ContentValues (value extracted querying the Android Content Provider) * * @param contentValues information extracted from the content provider * @return the EventInfo representation of the {@code contentValues} * @throws IllegalArgumentException if the {@code contentValues} cannot be parsed to a EventInfo object */ public static EventInfo fromContentValues(ContentValues contentValues) { try { EventInfo eventInfo = new EventInfo(); eventInfo.id = contentValues.getAsLong(Instances.EVENT_ID); eventInfo.calendarId = contentValues.getAsInteger(Instances.CALENDAR_ID); eventInfo.calendarDisplayName = contentValues.getAsString(Instances.CALENDAR_DISPLAY_NAME); eventInfo.title = contentValues.getAsString(Instances.TITLE); eventInfo.description = contentValues.getAsString(Instances.DESCRIPTION); eventInfo.startDate = new Date(JulianDate.toDate(contentValues.getAsLong(Instances.START_DAY)).getTime() + contentValues.getAsInteger(Instances.START_MINUTE) * MINUTE_IN_MILLISECOND); eventInfo.endDate = new Date(JulianDate.toDate(contentValues.getAsLong(Instances.END_DAY)).getTime() + contentValues.getAsInteger(Instances.END_MINUTE) * MINUTE_IN_MILLISECOND); eventInfo.allDay = contentValues.getAsInteger(Instances.ALL_DAY) == 1; eventInfo.location = contentValues.getAsString(Instances.EVENT_LOCATION); if (contentValues.getAsString(Instances.RRULE) == null && contentValues.getAsString(Instances.RDATE) == null) { eventInfo.recurrenceRule = null; } else { eventInfo.recurrenceRule = new RecurrenceRule() .setRrule(contentValues.getAsString(Instances.RRULE)) .setRdate(contentValues.getAsString(Instances.RDATE)) .setExrule(contentValues.getAsString(Instances.EXRULE)) .setExdate(contentValues.getAsString(Instances.EXDATE)); } return eventInfo; } catch (NullPointerException e) { StringBuilder errorString = new StringBuilder(); StringBuilder missingColumns = new StringBuilder(); errorString.append("There is NOT all the required parameters in the contentValues\nThe required keys are: "); for (String col : COLUMN) { errorString.append(col).append(", "); if (!contentValues.containsKey(col)) { missingColumns.append(col).append(", "); } } errorString.setLength(errorString.length() - 2); if (missingColumns.length() > 0) { missingColumns.setLength(missingColumns.length() - 2); } errorString.append("\n the following columns are missing: ").append(missingColumns); throw new IllegalArgumentException(errorString.toString()); } }
private void getEntry() { boolean first = false, calendar = false; String ID; long begin, end; String[] fields = { Instances.TITLE, Instances.BEGIN, Instances.END, Instances.EVENT_LOCATION, Instances.CALENDAR_ID }; long now = System.currentTimeMillis(); int i, j, calendar_no = calendars.length; Cursor eventCursor; currentRead = now - polltime; // query anything between now-polltime and now if (Build.VERSION.SDK_INT >= 14) eventCursor = CalendarContract.Instances.query( myStress.getContentResolver(), fields, currentRead, now + 24 * 60 * 60 * 1000); else { Uri.Builder builder = Uri.parse( "content://com.android.calendar/instances/when") .buildUpon(); ContentUris.appendId(builder, currentRead); ContentUris.appendId(builder, now + 24 * 60 * 60 * 1000); eventCursor = myStress.getContentResolver().query( builder.build(), new String[] { "title", "begin", "end", "eventLocation", "calendar_id" }, null, null, null); } // walk through all returns eventCursor.moveToFirst(); for (i = 0; i < eventCursor.getCount(); i++) { begin = eventCursor.getLong(1); end = eventCursor.getLong(2); ID = eventCursor.getString(4); calendar = false; // see if the entry is from the calendars I want for (j = 0; j < calendar_no; j++) if (calendars[j].compareTo(ID) == 0) { calendar = true; break; } if (calendar == true) // is this something new? if (begin > currentRead && begin < now) { if (first == false) { reading.append(String.valueOf(begin) + ":"+ String.valueOf(end)); first = true; } else reading.append("::" + String.valueOf(begin) + ":" + String.valueOf(end)); } eventCursor.moveToNext(); } // free data eventCursor.close(); // have we read anything? -> if not, delete reading string if (first == false) reading = null; }
@Override @TargetApi(KITKAT) protected void onHandleIntent(Intent intent) { InstanceDao instanceDao = new InstanceDao(getApplicationContext()); int instanceId = intent.getIntExtra(_ID, 0); Instance instance = instanceDao.get(instanceId); if (instance == null || instance.isRunning()) { return; } AudioManager audioManager = (AudioManager) getApplicationContext().getSystemService(Context.AUDIO_SERVICE); Log.d(MutePhoneBroadcastReceiver.class.getCanonicalName(), "Muting phone"); int currentRingerMode = audioManager.getRingerMode(); audioManager.setRingerMode(AudioManager.RINGER_MODE_SILENT); long endDate = intent.getLongExtra(Instances.DTEND, 0); long activeAfterEvents = Setting.getActiveAfterEvents(getApplicationContext()); Calendar calendar = Calendar.getInstance(); calendar.setTimeInMillis(endDate + activeAfterEvents); Intent unmuteIntent = new Intent(getApplicationContext(), UnmutePhoneBroadcastReceiver.class); unmuteIntent.setAction(UNMUTE); unmuteIntent.putExtra(PREVIOUS_RINGER_MODE, currentRingerMode); unmuteIntent.putExtra(_ID, instanceId); PendingIntent pendingIntent = PendingIntent.getBroadcast(getApplicationContext(), instanceId, unmuteIntent, PendingIntent.FLAG_CANCEL_CURRENT); AlarmManager alarmManager = (AlarmManager) getApplicationContext().getSystemService(Context.ALARM_SERVICE); alarmManager.cancel(pendingIntent); if (SDK_INT >= KITKAT) { alarmManager.setExact(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pendingIntent); } else { alarmManager.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pendingIntent); } instanceDao.setRunning(instanceId, true); }
/** * Loads <i>days</i> days worth of instances starting at <i>startDay</i>. */ public static void loadEvents(Context context, ArrayList<Event> events, int startDay, int days, int requestId, AtomicInteger sequenceNumber) { if (PROFILE) { Debug.startMethodTracing("loadEvents"); } Cursor cEvents = null; Cursor cAllday = null; events.clear(); try { int endDay = startDay + days - 1; // We use the byDay instances query to get a list of all events for // the days we're interested in. // The sort order is: events with an earlier start time occur // first and if the start times are the same, then events with // a later end time occur first. The later end time is ordered // first so that long rectangles in the calendar views appear on // the left side. If the start and end times of two events are // the same then we sort alphabetically on the title. This isn't // required for correctness, it just adds a nice touch. // Respect the preference to show/hide declined events SharedPreferences prefs = GeneralPreferences.getSharedPreferences(context); boolean hideDeclined = prefs.getBoolean(GeneralPreferences.KEY_HIDE_DECLINED, false); String where = EVENTS_WHERE; String whereAllday = ALLDAY_WHERE; if (hideDeclined) { String hideString = " AND " + Instances.SELF_ATTENDEE_STATUS + "!=" + Attendees.ATTENDEE_STATUS_DECLINED; where += hideString; whereAllday += hideString; } cEvents = instancesQuery(context.getContentResolver(), EVENT_PROJECTION, startDay, endDay, where, null, SORT_EVENTS_BY); cAllday = instancesQuery(context.getContentResolver(), EVENT_PROJECTION, startDay, endDay, whereAllday, null, SORT_ALLDAY_BY); // Check if we should return early because there are more recent // load requests waiting. if (requestId != sequenceNumber.get()) { return; } buildEventsFromCursor(events, cEvents, context, startDay, endDay); buildEventsFromCursor(events, cAllday, context, startDay, endDay); } finally { if (cEvents != null) { cEvents.close(); } if (cAllday != null) { cAllday.close(); } if (PROFILE) { Debug.stopMethodTracing(); } } }