private void addEventToCalendar(ColegiElectoral colegiElectoral) { Calendar calendar = Calendar.getInstance(Locale.getDefault()); calendar.set(2017, Calendar.OCTOBER, 1, 9, 0); Intent intent = new Intent(Intent.ACTION_EDIT); intent.setType("vnd.android.cursor.item/event"); intent.putExtra(CalendarContract.Events.TITLE, StringsManager.getString("notification_title")); intent.putExtra(CalendarContract.EXTRA_EVENT_BEGIN_TIME, calendar.getTimeInMillis()); intent.putExtra(CalendarContract.Events.ALL_DAY, true); String location = colegiElectoral.getLocal() + ": " + colegiElectoral.getAdresa() + ", " + colegiElectoral.getMunicipi(); intent.putExtra(CalendarContract.Events.EVENT_LOCATION, location); startActivity(intent); }
@TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH) public void addEventOnCalendar(PersianDate persianDate) { Intent intent = new Intent(Intent.ACTION_INSERT); intent.setData(CalendarContract.Events.CONTENT_URI); CivilDate civil = DateConverter.persianToCivil(persianDate); intent.putExtra(CalendarContract.Events.DESCRIPTION, mPersianCalendarHandler.dayTitleSummary(persianDate)); Calendar time = Calendar.getInstance(); time.set(civil.getYear(), civil.getMonth() - 1, civil.getDayOfMonth()); intent.putExtra(CalendarContract.EXTRA_EVENT_BEGIN_TIME, time.getTimeInMillis()); intent.putExtra(CalendarContract.EXTRA_EVENT_END_TIME, time.getTimeInMillis()); intent.putExtra(CalendarContract.EXTRA_EVENT_ALL_DAY, true); startActivity(intent); }
private long findLocalCalendar() throws android.os.RemoteException, android.database.sqlite.SQLiteException { Cursor cur = mContext.getContentProviderClient().query( CalendarContract.Calendars.CONTENT_URI, new String[]{ CalendarContract.Calendars._ID }, String.format("((%s = ?) AND (%s = ?) AND (%s = ?) AND (%s = ?))", CalendarContract.Calendars.ACCOUNT_NAME, CalendarContract.Calendars.ACCOUNT_TYPE, CalendarContract.Calendars.OWNER_ACCOUNT, CalendarContract.Calendars.NAME), new String[]{ mContext.getAccount().name, mContext.getContext().getString(R.string.account_type), mContext.getAccount().name, mType.id()}, null); long result = -1; if (cur != null) { if (cur.moveToNext()) { result = cur.getLong(0); } cur.close(); } return result; }
private HashMap<String /* FBID */, Long /* local ID */ > fetchLocalEvents( String selectorQuery, String[] selectorValues) throws android.os.RemoteException, android.database.sqlite.SQLiteException { HashMap<String, Long> localIds = new HashMap<>(); // HACK: Only select future events: Facebook will remove the events from the listing once // they pass, but it's desirable that we keep them in the calendar. The only way to achieve // so is to ignore them Cursor cur = mContext.getContentProviderClient().query( CalendarContract.Events.CONTENT_URI, new String[]{ CalendarContract.Events.UID_2445, CalendarContract.Events._ID }, selectorQuery, selectorValues, null); if (cur != null) { while (cur.moveToNext()) { localIds.put(cur.getString(0), cur.getLong(1)); } cur.close(); } return localIds; }
private HashMap<Integer /* minutes */, Long /* reminder ID */> getLocalReminders(SyncContext context, long localEventId) throws android.os.RemoteException, android.database.sqlite.SQLiteException { Cursor cur = context.getContentProviderClient().query( CalendarContract.Reminders.CONTENT_URI, new String[]{ CalendarContract.Reminders._ID, CalendarContract.Reminders.MINUTES }, String.format("(%s = ?)", CalendarContract.Reminders.EVENT_ID), new String[]{ String.valueOf(localEventId) }, null); @SuppressLint("UseSparseArrays") HashMap<Integer /* minutes */, Long /* reminder ID */> localReminders = new HashMap<>(); if (cur != null) { while (cur.moveToNext()) { localReminders.put(cur.getInt(1), cur.getLong(0)); } cur.close(); } return localReminders; }
private void createReminders(SyncContext context, long localEventId, Set<Integer> reminders) throws android.os.RemoteException, android.database.sqlite.SQLiteException { ArrayList<ContentValues> reminderValues = new ArrayList<>(); for (int reminder : reminders) { ContentValues values = new ContentValues(); values.put(CalendarContract.Reminders.EVENT_ID, localEventId); values.put(CalendarContract.Reminders.METHOD, CalendarContract.Reminders.METHOD_ALERT); values.put(CalendarContract.Reminders.MINUTES, reminder); reminderValues.add(values); } Uri uri = CalendarContract.Reminders.CONTENT_URI.buildUpon() .appendQueryParameter(CalendarContract.CALLER_IS_SYNCADAPTER, "true") .appendQueryParameter(CalendarContract.Calendars.ACCOUNT_NAME, context.getAccount().name) .appendQueryParameter(CalendarContract.Calendars.ACCOUNT_TYPE, context.getContext().getString(R.string.account_type)) .build(); context.getContentProviderClient().bulkInsert( uri, reminderValues.toArray(new ContentValues[0])); }
public void setReminder(ContentResolver cr, long eventID, int timeBefore) { try { ContentValues values = new ContentValues(); values.put(CalendarContract.Reminders.MINUTES, timeBefore); values.put(CalendarContract.Reminders.EVENT_ID, eventID); values.put(CalendarContract.Reminders.METHOD, CalendarContract.Reminders.METHOD_ALERT); Uri uri = cr.insert(CalendarContract.Reminders.CONTENT_URI, values); Cursor c = CalendarContract.Reminders.query(cr, eventID, new String[]{CalendarContract.Reminders.MINUTES}); if (c.moveToFirst()) { System.out.println("calendar" + c.getInt(c.getColumnIndex(CalendarContract.Reminders.MINUTES))); } c.close(); } catch (Exception e) { e.printStackTrace(); } }
@TargetApi(14) private void openCalendar(JSONArray args) { try { final Long millis = args.getJSONObject(0).optLong("date"); cordova.getThreadPool().execute(new Runnable() { @Override public void run() { final Uri.Builder builder = CalendarContract.CONTENT_URI.buildUpon().appendPath("time"); ContentUris.appendId(builder, millis); final Intent intent = new Intent(Intent.ACTION_VIEW).setData(builder.build()); Calendar.this.cordova.startActivityForResult(Calendar.this, intent, RESULT_CODE_OPENCAL); callback.success(); } }); } catch (JSONException e) { System.err.println("Exception: " + e.getMessage()); callback.error(e.getMessage()); } }
@SuppressWarnings("MissingPermission") // already requested in calling method public void deleteCalendar(String calendarName) { try { Uri evuri = CalendarContract.Calendars.CONTENT_URI; final ContentResolver contentResolver = cordova.getActivity().getContentResolver(); Cursor result = contentResolver.query(evuri, new String[]{CalendarContract.Calendars._ID, CalendarContract.Calendars.NAME, CalendarContract.Calendars.CALENDAR_DISPLAY_NAME}, null, null, null); if (result != null) { while (result.moveToNext()) { if (result.getString(1).equals(calendarName) || result.getString(2).equals(calendarName)) { long calid = result.getLong(0); Uri deleteUri = ContentUris.withAppendedId(evuri, calid); contentResolver.delete(deleteUri, null, null); } } result.close(); } // also delete previously crashing calendars, see https://github.com/EddyVerbruggen/Calendar-PhoneGap-Plugin/issues/241 deleteCrashingCalendars(contentResolver); } catch (Throwable t) { System.err.println(t.getMessage()); t.printStackTrace(); } }
@Override protected void buildEvent(Event recurrence, ContentProviderOperation.Builder builder) { super.buildEvent(recurrence, builder); boolean buildException = recurrence != null; Event eventToBuild = buildException ? recurrence : event; builder.withValue(COLUMN_UID, event.uid) .withValue(COLUMN_SEQUENCE, eventToBuild.sequence) .withValue(CalendarContract.Events.DIRTY, 0) .withValue(CalendarContract.Events.DELETED, 0); if (buildException) { builder.withValue(CalendarContract.Events.ORIGINAL_SYNC_ID, fileName); } else { builder.withValue(CalendarContract.Events._SYNC_ID, fileName) .withValue(COLUMN_ETAG, eTag); } }
/** * fetching all calendars from local android calendar db * * @return a set of all calendars */ public Set<String> getCalendars() { // Fetch a list of all calendars sync'd with the device and their display names Cursor cursor = contentResolver.query(CALENDAR_URI, FIELDS, null, null, null); try { if (cursor.getCount() > 0) { while (cursor.moveToNext()) { String name = cursor.getString(0); String displayName = cursor.getString(1); // This is actually a better pattern: String color = cursor.getString(cursor.getColumnIndex(CalendarContract.Calendars.CALENDAR_COLOR)); Boolean selected = !cursor.getString(3).equals("0"); calendars.add(displayName); } } } catch (AssertionError ex) { /*TODO: log exception and bail*/ } return calendars; }
public String getCalendarIdForName(String calendarName) { String selection = "(" + CalendarContract.Calendars.NAME + " = ?)"; String[] selectionArgs = new String[] {calendarName}; Cursor cursor = contentResolver.query(CALENDAR_URI, FIELDS, selection, selectionArgs, null); try { if (cursor.getCount() > 0) { while (cursor.moveToNext()) { String id = cursor.getString(0); return id; } } } catch (AssertionError ex) { /*TODO: log exception and bail*/ } return ""; }
private boolean ensureCalendarPermissions() { if (ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_CALENDAR) != PackageManager.PERMISSION_GRANTED || ActivityCompat.checkSelfPermission(this, Manifest.permission.WRITE_CALENDAR) != PackageManager.PERMISSION_GRANTED) { ActivityCompat.requestPermissions(this, new String[] { Manifest.permission.READ_CALENDAR, Manifest.permission.WRITE_CALENDAR }, 0); return false; } if (mCalendarsClient == null) { mCalendarsClient = getContentResolver().acquireContentProviderClient(CalendarContract.AUTHORITY); mCalendarQueue = new BasicOperationsQueue(mCalendarsClient); } return true; }
public static Uri create(@NonNull Account account, @NonNull ContentProviderClient provider, @NonNull CollectionInfo info) throws CalendarStorageException { ContentValues values = valuesFromCollectionInfo(info, true); // ACCOUNT_NAME and ACCOUNT_TYPE are required (see docs)! If it's missing, other apps will crash. values.put(CalendarContract.Calendars.ACCOUNT_NAME, account.name); values.put(CalendarContract.Calendars.ACCOUNT_TYPE, account.type); values.put(CalendarContract.Calendars.OWNER_ACCOUNT, account.name); // flag as visible & synchronizable at creation, might be changed by user at any time values.put(CalendarContract.Calendars.VISIBLE, 0); values.put(CalendarContract.Calendars.SYNC_EVENTS, 1); return create(account, provider, values); }
@Override public LocalResource[] getDirty() throws CalendarStorageException, FileNotFoundException { List<LocalResource> dirty = new LinkedList<>(); // get dirty events which are required to have an increased SEQUENCE value for (LocalEvent event : (LocalEvent[]) queryEvents( CalendarContract.Events.DIRTY + "!=0 AND " + CalendarContract.Events.ORIGINAL_ID + " IS NULL", null)) { if (event.getEvent().sequence == null) // sequence has not been assigned yet (i.e. this event was just locally created) { event.getEvent().sequence = 0; } else if (event.weAreOrganizer) { event.getEvent().sequence++; } dirty.add(event); } return dirty.toArray(new LocalResource[dirty.size()]); }
@Test public void testSelection() throws Exception { TransactionContext mockTc = failingMock(TransactionContext.class); SoftRowReference<CalendarContract.Calendars> dummyReference = dummy(SoftRowReference.class); RowSnapshot<CalendarContract.Calendars> mockCalendarRow = failingMock(RowSnapshot.class); doReturn(dummyReference).when(mockCalendarRow).reference(); doReturn(new BackReference<>(dummy(Uri.class), 12)).when(mockTc).resolved(dummyReference); assertThat(new CalendarScoped(mockCalendarRow, new EqArg("x", "y")), predicateWith( selection(mockTc, "( x = ? ) and ( calendar_id = ? )"), argumentValues(mockTc, "y", "-1"), backReferences(mockTc, AbsentMatcher.<Integer>isAbsent(), isPresent(12)) )); }
static public void requestSync(Context context) { String accountType = context.getResources().getString(R.string.account_type); Logger logger = Logger.getInstance(context); for (Account account : AccountManager.get(context).getAccountsByType(accountType)){ Bundle extras = new Bundle(); extras.putBoolean(ContentResolver.SYNC_EXTRAS_MANUAL, true); extras.putBoolean(ContentResolver.SYNC_EXTRAS_EXPEDITED, true); ContentResolver.requestSync(account, CalendarContract.AUTHORITY, extras); logger.info(TAG, "Explicitly requested sync for account %s", account.name); } }
private void updateLocalCalendar() throws android.os.RemoteException, android.database.sqlite.SQLiteException { ContentValues values = new ContentValues(); values.put(CalendarContract.Calendars.CALENDAR_COLOR, getCalendarColor()); mContext.getContentProviderClient().update( CalendarContract.Calendars.CONTENT_URI, values, String.format("(%s = ?)", CalendarContract.Calendars._ID), new String[] { String.valueOf(mLocalCalendarId) }); }
public void deleteLocalCalendar() throws android.os.RemoteException, android.database.sqlite.SQLiteException { mContext.getContentProviderClient().delete( CalendarContract.Calendars.CONTENT_URI, String.format("(%s = ?)", CalendarContract.Calendars._ID), new String[] { String.valueOf(mLocalCalendarId) }); }
private HashMap<String /* FBID */, Long /* local ID */ > fetchLocalPastEvents() throws android.os.RemoteException, android.database.sqlite.SQLiteException { return fetchLocalEvents( String.format("((%s = ?) AND (%s < ?))", CalendarContract.Events.CALENDAR_ID, CalendarContract.Events.DTSTART), new String[]{ String.valueOf(mLocalCalendarId), String.valueOf(Calendar.getInstance().getTimeInMillis()) }); }
private HashMap<String /* FBID */, Long /* local ID */ > fetchLocalFutureEvents() throws android.os.RemoteException, android.database.sqlite.SQLiteException { return fetchLocalEvents( String.format("((%s = ?) AND (%s >= ?))", CalendarContract.Events.CALENDAR_ID, CalendarContract.Events.DTSTART), new String[] { String.valueOf(mLocalCalendarId), String.valueOf(Calendar.getInstance().getTimeInMillis()) }); }
public int availability() { switch (mType) { case TYPE_NOT_REPLIED: case TYPE_DECLINED: case TYPE_BIRTHDAY: return CalendarContract.Events.AVAILABILITY_FREE; case TYPE_MAYBE: return CalendarContract.Events.AVAILABILITY_TENTATIVE; case TYPE_ATTENDING: return CalendarContract.Events.AVAILABILITY_BUSY; } return CalendarContract.Events.AVAILABILITY_BUSY; }
private void removeReminder(SyncContext context, long localReminderId) throws android.os.RemoteException, android.database.sqlite.SQLiteException { context.getContentProviderClient().delete( CalendarContract.Reminders.CONTENT_URI, String.format("(%s = ?)", CalendarContract.Reminders._ID ), new String[]{ String.valueOf(localReminderId) }); }
public void update(SyncContext context, long localEventId) throws android.os.RemoteException, android.database.sqlite.SQLiteException { ContentValues values = new ContentValues(mValues); values.remove(CalendarContract.Events._ID); values.remove(CalendarContract.Events.UID_2445); values.remove(CalendarContract.Events.CALENDAR_ID); context.getContentProviderClient().update( CalendarContract.Events.CONTENT_URI.buildUpon() .appendQueryParameter(CalendarContract.SyncState.ACCOUNT_TYPE, context.getContext().getString(R.string.account_type)) .appendQueryParameter(CalendarContract.SyncState.ACCOUNT_NAME, context.getAccount().name) .appendQueryParameter(CalendarContract.CALLER_IS_SYNCADAPTER, "true") .build(), values, String.format("(%s = ?)", CalendarContract.Events._ID), new String[] { String.valueOf(localEventId) }); HashMap<Integer /* minutes */, Long /* reminder ID */> reminders = getLocalReminders(context, localEventId); Set<Integer> localReminderSet = reminders.keySet(); Set<Integer> configuredReminders = mCalendar.getReminderIntervals(); // Silly Java can't even subtract Sets...*sigh* Set<Integer> toAdd = new HashSet<>(); toAdd.addAll(configuredReminders); toAdd.removeAll(localReminderSet); Set<Integer> toRemove = new HashSet<>(); toRemove.addAll(localReminderSet); toRemove.removeAll(configuredReminders); if (!toAdd.isEmpty()) { createReminders(context, localEventId, toAdd); } for (int reminder : toRemove) { removeReminder(context, reminders.get(reminder)); } }
@RequiresPermission(Manifest.permission.READ_CALENDAR) private void getCalendarInfo() { Cursor c; c = this.getContext().getContentResolver().query( CalendarContract.Events.CONTENT_URI, new String[]{CalendarContract.Events._ID, CalendarContract.Events.TITLE, CalendarContract.Events.DTSTART, CalendarContract.Events.EVENT_LOCATION, CalendarContract.Events.DURATION}, null, null, null ); if (c != null && c.getCount() > 0) { c.moveToFirst(); while (!c.isAfterLast()) { String id = c.getString(c.getColumnIndex( CalendarContract.Events._ID)); String title = c.getString(c.getColumnIndex( CalendarContract.Events.TITLE)); Long startTime = c.getLong(c.getColumnIndex(CalendarContract.Events.DTSTART)); Long endTime = c.getLong(c.getColumnIndex(CalendarContract.Events.DTEND)); String location = c.getString(c.getColumnIndex(CalendarContract.Events.EVENT_LOCATION)); String duration = c.getString(c.getColumnIndex(CalendarContract.Events.DURATION)); CalendarEvent calendarEvent = new CalendarEvent(id, title, startTime, endTime, duration, location); output(calendarEvent); c.moveToNext(); } c.close(); } }
/** * Gets the currently-logged in user's Google Calendar, or the Google Calendar for the user * specified in the given intent's {@link #EXTRA_ACCOUNT_NAME}. */ private long getCalendarId(Intent intent) { final String accountName; if (intent != null && intent.hasExtra(EXTRA_ACCOUNT_NAME)) { accountName = intent.getStringExtra(EXTRA_ACCOUNT_NAME); } else { accountName = AccountUtils.getActiveAccountName(this); } if (TextUtils.isEmpty(accountName)) { return INVALID_CALENDAR_ID; } // TODO: The calendar ID should be stored in shared settings_prefs upon choosing an account. Cursor calendarsCursor = getContentResolver().query( CalendarContract.Calendars.CONTENT_URI, new String[]{"_id"}, // TODO: What if the calendar is not displayed or not sync'd? "account_name = ownerAccount and account_name = ?", new String[]{accountName}, null); long calendarId = INVALID_CALENDAR_ID; if (calendarsCursor != null && calendarsCursor.moveToFirst()) { calendarId = calendarsCursor.getLong(0); calendarsCursor.close(); } return calendarId; }
@Test public void test() { assertThat(new AttendeesProjection(), projects( CalendarContract.Attendees._ID, CalendarContract.Attendees.ATTENDEE_EMAIL, CalendarContract.Attendees.ATTENDEE_NAME, CalendarContract.Attendees.ATTENDEE_RELATIONSHIP, CalendarContract.Attendees.ATTENDEE_STATUS, CalendarContract.Attendees.ATTENDEE_TYPE)); }
@SuppressWarnings("MissingPermission") // already requested in calling method private void deleteCrashingCalendars(ContentResolver contentResolver) { // first find any faulty Calendars final String fixingAccountName = "FixingAccountName"; String selection = CalendarContract.Calendars.ACCOUNT_NAME + " IS NULL"; Uri uri = CalendarContract.Calendars.CONTENT_URI; uri = uri.buildUpon() .appendQueryParameter(CalendarContract.CALLER_IS_SYNCADAPTER, "true") .appendQueryParameter(CalendarContract.Calendars.ACCOUNT_NAME, fixingAccountName) .appendQueryParameter(CalendarContract.Calendars.ACCOUNT_TYPE, CalendarContract.ACCOUNT_TYPE_LOCAL) .build(); ContentValues values = new ContentValues(); values.put(CalendarContract.Calendars.ACCOUNT_NAME, fixingAccountName); values.put(CalendarContract.Calendars.ACCOUNT_TYPE, CalendarContract.ACCOUNT_TYPE_LOCAL); int count = contentResolver.update(uri, values, selection, null); // now delete any faulty Calendars if (count > 0) { Uri evuri = CalendarContract.Calendars.CONTENT_URI; Cursor result = contentResolver.query(evuri, new String[]{CalendarContract.Calendars._ID, CalendarContract.Calendars.ACCOUNT_NAME}, null, null, null); if (result != null) { while (result.moveToNext()) { if (result.getString(1).equals(fixingAccountName)) { long calid = result.getLong(0); Uri deleteUri = ContentUris.withAppendedId(evuri, calid); contentResolver.delete(deleteUri, null, null); } } result.close(); } } }
protected LocalEvent(@NonNull AndroidCalendar calendar, long id, ContentValues baseInfo) { super(calendar, id, baseInfo); if (baseInfo != null) { fileName = baseInfo.getAsString(CalendarContract.Events._SYNC_ID); eTag = baseInfo.getAsString(COLUMN_ETAG); } }
@NonNull @Override public ContentProviderOperation.Builder updatedBuilder(TransactionContext transactionContext, @NonNull ContentProviderOperation.Builder builder) { return builder.withValue(CalendarContract.Reminders.MINUTES, mMinutes) .withValue(CalendarContract.Reminders.METHOD, mMethod); }
@NonNull @Override public Cursor rows(@NonNull UriParams uriParams, @NonNull Projection<CalendarContract.Events> projection, @NonNull Predicate predicate, @NonNull Optional<String> sorting) throws RemoteException { return mDelegate.rows( uriParams, projection, new org.dmfs.android.calendarpal.predicates.CalendarScoped(mCalendarRow, predicate), sorting); }
public TransientEventsCleanup(@NonNull Table<CalendarContract.Events> eventsTable) { // wipe all events without sync sync id which have been deleted mDelegate = new BulkDelete<>(eventsTable, new AllOf( new IsNull(CalendarContract.Events.ORIGINAL_SYNC_ID), new IsNull(CalendarContract.Events._SYNC_ID), new EqArg(CalendarContract.Events.DELETED, 1))); }
public AttendeesProjection() { super(new MultiProjection<CalendarContract.Attendees>( CalendarContract.Attendees._ID, CalendarContract.Attendees.ATTENDEE_EMAIL, CalendarContract.Attendees.ATTENDEE_NAME, CalendarContract.Attendees.ATTENDEE_RELATIONSHIP, CalendarContract.Attendees.ATTENDEE_STATUS, CalendarContract.Attendees.ATTENDEE_TYPE)); }
@NonNull @Override public ContentProviderOperation.Builder updatedBuilder(TransactionContext transactionContext, @NonNull ContentProviderOperation.Builder builder) { return mDelegate.updatedBuilder(transactionContext, builder) .withValue(CalendarContract.Attendees.ATTENDEE_NAME, mName == null ? null : mName.toString()); }
@NonNull @Override public ContentProviderOperation.Builder updatedBuilder(TransactionContext transactionContext, @NonNull ContentProviderOperation.Builder builder) { return builder.withValue(CalendarContract.Attendees.ATTENDEE_EMAIL, mAttendeeEmail.toString()) .withValue(CalendarContract.Attendees.ATTENDEE_TYPE, mType) .withValue(CalendarContract.Attendees.ATTENDEE_STATUS, mStatus) .withValue(CalendarContract.Attendees.ATTENDEE_RELATIONSHIP, mRelationShip); }
@NonNull @Override public ContentProviderOperation.Builder updatedBuilder(TransactionContext transactionContext, @NonNull ContentProviderOperation.Builder builder) { return mDelegate.updatedBuilder(transactionContext, builder) .withValue(CalendarContract.Events.ORGANIZER, mOrganizer == null ? null : mOrganizer.toString()); }
@NonNull @Override public ContentProviderOperation.Builder updatedBuilder(TransactionContext transactionContext, @NonNull ContentProviderOperation.Builder builder) { return mDelegate.updatedBuilder(transactionContext, builder) .withValue(CalendarContract.Events.DESCRIPTION, mDescription == null ? null : mDescription.toString()); }