Google doesn’t officially recommend using internal Calendar APIs, but sometimes there’s no other way to achieve certain tasks. Here’s how to add calendar events programmatically across different Android versions.

The Provider URI Challenge

The main challenge is that the Calendar content provider URI changed between Android versions:

  • Pre-Froyo (< 2.2): content://calendar/events
  • Froyo and above (≥ 2.2): content://com.android.calendar/events

The Solution

Here’s a version-agnostic approach to adding calendar events:

private Uri getCalendarUri() {
    if (Build.VERSION.SDK_INT >= 8) {
        return Uri.parse("content://com.android.calendar/events");
    }
    return Uri.parse("content://calendar/events");
}

public void addCalendarEvent(String title, String description,
                              long startTime, long endTime) {
    ContentResolver cr = getContentResolver();
    ContentValues values = new ContentValues();

    values.put("calendar_id", 1);
    values.put("title", title);
    values.put("description", description);
    values.put("dtstart", startTime);
    values.put("dtend", endTime);
    values.put("eventTimezone", TimeZone.getDefault().getID());

    Uri eventUri = cr.insert(getCalendarUri(), values);

    if (eventUri != null) {
        Log.d("Calendar", "Event created: " + eventUri.toString());
    }
}

Required Permissions

Don’t forget to add the calendar permissions to your AndroidManifest.xml:

<uses-permission android:name="android.permission.READ_CALENDAR" />
<uses-permission android:name="android.permission.WRITE_CALENDAR" />

Important Notes

  1. This uses undocumented APIs that may change
  2. Always check for null returns from insert()
  3. Consider using the Calendar Intent for a more stable approach when user interaction is acceptable

The Intent-based approach is more reliable for user-facing features, but programmatic insertion is useful for background sync scenarios.