fiddler fiddler - 1 month ago 7x
Android Question

Specify calendar in Android event creation intent

I trigger the creation of a calendar event through the following piece of code:

Intent intent = new Intent(Intent.ACTION_INSERT);

But I would like to specifiy which calendar should be used for the event creation (i.e set the initial value of the calendar dropdown in the event creation screen).

I've tried to provide

intent.putExtra(CalendarContract.Events.ACCOUNT_TYPE, accountType);
intent.putExtra(CalendarContract.Events.ACCOUNT_NAME, accountName);
intent.putExtra(CalendarContract.Events.CALENDAR_ID, calendarId);

but it has no effect on the calendar dropdown initial value.

Is it possible to specify a calendar in the event creation intent?


I believe, there is no reliable way to achieve this with just an Intent. You may come across all sorts of calendar apps that may or may not support this.

If you don't mind if the user can not change the calendar you can achieve this with a simple trick:

Just create a "placeholder" event in the calendar you want to (like outlined in the Android Developer Guide) and fire an Intent.ACTION_EDIT Intent for this event instead.

Here is some (untested) code to show how this could work:

ContentResolver cr = getContentResolver();
ContentValues values = new ContentValues();

// provide an initial time
long now=System.currentTimeMillis();
values.put(Events.DTSTART, now);
values.put(Events.DTEND, now+3600000);
values.put(Events.TITLE, "");
values.put(Events.CALENDAR_ID, calendarId);
values.put(Events.EVENT_TIMEZONE, TimeZone.getDefault().getId());

// create the "placeholder" event
Uri uri = cr.insert(Events.CONTENT_URI, values);

// get the event ID that is the last element in the Uri
long eventId = Long.parseLong(uri.getLastPathSegment());

// launch the editor to edit the "placeholder" event
Intent intent = new Intent(Intent.ACTION_EDIT);
intent.setData(ContentUirs.withAppendedId(CalendarContract.Events.CONTENT_URI, eventId));
startActivityForResult(intent, 0);

The edit Intent probably doesn't return a status that tells you if the event has been saved or if the user dismissed the editor without saving. So you should read back the event and check if it has been modified by the user and delete it if it has not been changed.