166

I'm just getting up to speed on Android, and today in a project meeting someone said that Android has no native calendar app so users just use whatever calendar app they like.

Is this true, and if so how do I programmatically add an event to the user's calendar? Is there a common API they all share?

For what it's worth, we're probably targeting Android 2.x.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Peter Nelson
  • 5,917
  • 17
  • 43
  • 62
  • You should probably accept oriharel's answer since he provides the code to accomplish your task. – jww Feb 20 '17 at 02:52
  • 1
    @SumitSharma your link seems to no longer work -- and seems pretty suspect with the automatic install dialog. – fix Feb 24 '19 at 03:49

12 Answers12

299

Try this in your code:

Calendar cal = Calendar.getInstance();              
Intent intent = new Intent(Intent.ACTION_EDIT);
intent.setType("vnd.android.cursor.item/event");
intent.putExtra("beginTime", cal.getTimeInMillis());
intent.putExtra("allDay", true);
intent.putExtra("rrule", "FREQ=YEARLY");
intent.putExtra("endTime", cal.getTimeInMillis()+60*60*1000);
intent.putExtra("title", "A Test Event from android app");
startActivity(intent);
Stan
  • 4,169
  • 2
  • 31
  • 39
oriharel
  • 10,418
  • 14
  • 48
  • 57
  • 6
    I like this solution a lot. Mainly because it pushes the user to select his/her own calendar (if he has more than one). – Sebastian Roth Dec 03 '10 at 07:38
  • 1
    Thanks. Does this also work with sense? No funky nonsense with HTC overriding calendars, etc? – Anthony Graglia Feb 02 '11 at 23:35
  • Using the code above, can I add a custom tone for the cal event notification? – worked Nov 24 '11 at 21:07
  • Any idea why intent.putExtra("endTime", cal.getTimeInMillis()+5*60*60*1000); doesn't work (it always makes one hour events, so the example above works, but not for different endTimes) – Julien Apr 18 '12 at 15:53
  • 2
    how to make this compatible for android 2.2? – Srikanth Pai Aug 24 '12 at 20:09
  • This is a great answer! Works on my app. One Question: Will this work on any device with a calendar app installed? – Daniel Casserly Dec 09 '12 at 22:55
  • @oriharel, Can you please explain this code , I had put this code but on running I'm getting application crash error...??. I had already given read and write calendar in the manifest file – Sumit Sharma Dec 10 '12 at 08:18
  • I want to start my app from calendar event, please help me how can I add a uri scheme to calendar event – Rizwan Sohaib Apr 01 '13 at 08:01
  • 15
    You should use .setData(CalendarContract.Events.CONTENT_URI) instead of setType, because with setType(string) it will crash on some devices! – Informatic0re Oct 02 '13 at 20:05
  • how do you also add location? @oriharel – Manny265 Jul 02 '14 at 16:17
  • @Julien try 5L * 60L * 60L * 1000L – Hamzeh Soboh Mar 22 '15 at 09:04
  • 4
    Full tutorial here: http://code.tutsplus.com/tutorials/android-essentials-adding-events-to-the-users-calendar--mobile-8363 It's better to use constants for avoiding typos ;) – Adrien Cadet Apr 02 '15 at 19:25
  • It works but it is very confusing for it's user when the user doesn't have a calendar account. Google wants to synchronize data online. – Codebeat Jun 02 '15 at 19:40
  • 7
    Your code tells your app to send data to another (calendar) app which then uses that data to add new calendar event. Your app does not write nor read calendar data, so you don't need any permissions in the manifest. – Singed Oct 05 '15 at 13:38
  • 1
    The hardcoded strings can be replaced by constants e.g: use CalendarContract.EXTRA_EVENT_BEGIN_TIME instead of "beginTime" and CalendarContract.Events.TITLE instead of "title". – Cristan Jul 19 '17 at 09:05
  • 1
    permissions are not necessary – Ehsan.R Aug 25 '17 at 17:47
66

Use this API in your code.. It will help u to insert event, event with reminder and event with meeting can be enabled... This api works for platform 2.1 and above Those who uses less then 2.1 instead of content://com.android.calendar/events use content://calendar/events

 public static long pushAppointmentsToCalender(Activity curActivity, String title, String addInfo, String place, int status, long startDate, boolean needReminder, boolean needMailService) {
    /***************** Event: note(without alert) *******************/

    String eventUriString = "content://com.android.calendar/events";
    ContentValues eventValues = new ContentValues();

    eventValues.put("calendar_id", 1); // id, We need to choose from
                                        // our mobile for primary
                                        // its 1
    eventValues.put("title", title);
    eventValues.put("description", addInfo);
    eventValues.put("eventLocation", place);

    long endDate = startDate + 1000 * 60 * 60; // For next 1hr

    eventValues.put("dtstart", startDate);
    eventValues.put("dtend", endDate);

    // values.put("allDay", 1); //If it is bithday alarm or such
    // kind (which should remind me for whole day) 0 for false, 1
    // for true
    eventValues.put("eventStatus", status); // This information is
    // sufficient for most
    // entries tentative (0),
    // confirmed (1) or canceled
    // (2):
    eventValues.put("eventTimezone", "UTC/GMT +2:00");
   /*Comment below visibility and transparency  column to avoid java.lang.IllegalArgumentException column visibility is invalid error */

    /*eventValues.put("visibility", 3); // visibility to default (0),
                                        // confidential (1), private
                                        // (2), or public (3):
    eventValues.put("transparency", 0); // You can control whether
                                        // an event consumes time
                                        // opaque (0) or transparent
                                        // (1).
      */
    eventValues.put("hasAlarm", 1); // 0 for false, 1 for true

    Uri eventUri = curActivity.getApplicationContext().getContentResolver().insert(Uri.parse(eventUriString), eventValues);
    long eventID = Long.parseLong(eventUri.getLastPathSegment());

    if (needReminder) {
        /***************** Event: Reminder(with alert) Adding reminder to event *******************/

        String reminderUriString = "content://com.android.calendar/reminders";

        ContentValues reminderValues = new ContentValues();

        reminderValues.put("event_id", eventID);
        reminderValues.put("minutes", 5); // Default value of the
                                            // system. Minutes is a
                                            // integer
        reminderValues.put("method", 1); // Alert Methods: Default(0),
                                            // Alert(1), Email(2),
                                            // SMS(3)

        Uri reminderUri = curActivity.getApplicationContext().getContentResolver().insert(Uri.parse(reminderUriString), reminderValues);
    }

    /***************** Event: Meeting(without alert) Adding Attendies to the meeting *******************/

    if (needMailService) {
        String attendeuesesUriString = "content://com.android.calendar/attendees";

        /********
         * To add multiple attendees need to insert ContentValues multiple
         * times
         ***********/
        ContentValues attendeesValues = new ContentValues();

        attendeesValues.put("event_id", eventID);
        attendeesValues.put("attendeeName", "xxxxx"); // Attendees name
        attendeesValues.put("attendeeEmail", "yyyy@gmail.com");// Attendee
                                                                            // E
                                                                            // mail
                                                                            // id
        attendeesValues.put("attendeeRelationship", 0); // Relationship_Attendee(1),
                                                        // Relationship_None(0),
                                                        // Organizer(2),
                                                        // Performer(3),
                                                        // Speaker(4)
        attendeesValues.put("attendeeType", 0); // None(0), Optional(1),
                                                // Required(2), Resource(3)
        attendeesValues.put("attendeeStatus", 0); // NOne(0), Accepted(1),
                                                    // Decline(2),
                                                    // Invited(3),
                                                    // Tentative(4)

        Uri attendeuesesUri = curActivity.getApplicationContext().getContentResolver().insert(Uri.parse(attendeuesesUriString), attendeesValues);
    }

    return eventID;

}
Amitabha Biswas
  • 3,281
  • 1
  • 11
  • 23
Pradeep
  • 2,530
  • 26
  • 37
  • this code is not working for me can anybody please provide me the proper solution for same issue? – Mahaveer Muttha Jan 11 '13 at 10:36
  • 01-11 16:06:01.928: E/AndroidRuntime(24027): java.lang.IllegalArgumentException: Event values must include an eventTimezone – Mahaveer Muttha Jan 11 '13 at 10:36
  • 4
    I added `event.put("eventTimezone", "UTC/GMT +2:00")` and eliminated `event.put("visibility", 3)` and `event.put("transparency", 0)` and it works well – validcat Sep 25 '13 at 10:11
  • 1
    Maybe get timezone error. I add this and its works eventValues.put("eventTimezone", TimeZone.getDefault().getID()); – Cüneyt Apr 06 '15 at 14:03
  • 2
    I am getting `android.database.sqlite.SQLiteException` at line `Uri reminderUri = curActivity.getApplicationContext().getContentResolver().insert(Uri.parse(reminderUriString), reminderValues);` – Sibidharan Mar 31 '16 at 15:02
  • This code not working for me. It always return eventId but calander app not showing that event to calendar. Please help me. – SANAT Jul 04 '16 at 16:46
  • @Pradeep awesome code! Thanks for that. In addition, to delete an event, one could do: String eventUriString = "content://com.android.calendar/events/" + eventId; int rowsDeleted = MainActivity.this.getApplicationContext().getContentResolver().delete(Uri.parse(eventUriString), null, null); – Hashim Akhtar Oct 25 '16 at 18:20
  • I am also getting eventId but calander app not showing that event in calendar. – Ravikumar11 Jan 02 '17 at 11:32
  • My data goes into birthday instead of events. any solution for that? @Amitabha Biswas – urvi joshi May 25 '17 at 07:47
  • Solved the problem https://stackoverflow.com/questions/44174699/data-entry-in-calender-from-my-application-entry-in-birthday-instead-of-events – urvi joshi May 25 '17 at 10:37
  • 1
    but one when i set values.put("rrule", "FREQ=DAILY"); and set endDate, its not working. event set for all days not till the end date. @AmitabhaBiswas – urvi joshi May 25 '17 at 10:39
  • 1
    values.put(CalendarContract.Reminders.CALENDAR_ID, 1); values.put(CalendarContract.Reminders.TITLE, "Routine Everyday1"); values.put(CalendarContract.Reminders.DTSTART, millisecondsTimesEveryday); values.put(CalendarContract.Reminders.HAS_ALARM, true); values.put("rrule", "FREQ=DAILY"); //UNTIL=1924885800000 values.put(CalendarContract.Reminders.DTEND, EndtimeInMilliseconds); @AmitabhaBiswas – urvi joshi May 25 '17 at 10:44
  • Thanks a lot for this code! Is there any column value I can add to auto generate a video meeting link with the calendar event using the CalendarProvider? – Haran Sivaram Aug 17 '20 at 01:36
59

i used the code below, it solves my problem to add event in default device calendar in ICS and also on version less that ICS

    if (Build.VERSION.SDK_INT >= 14) {
        Intent intent = new Intent(Intent.ACTION_INSERT)
        .setData(Events.CONTENT_URI)
        .putExtra(CalendarContract.EXTRA_EVENT_BEGIN_TIME, beginTime.getTimeInMillis())
        .putExtra(CalendarContract.EXTRA_EVENT_END_TIME, endTime.getTimeInMillis())
        .putExtra(Events.TITLE, "Yoga")
        .putExtra(Events.DESCRIPTION, "Group class")
        .putExtra(Events.EVENT_LOCATION, "The gym")
        .putExtra(Events.AVAILABILITY, Events.AVAILABILITY_BUSY)
        .putExtra(Intent.EXTRA_EMAIL, "rowan@example.com,trevor@example.com");
         startActivity(intent);
}

    else {
        Calendar cal = Calendar.getInstance();              
        Intent intent = new Intent(Intent.ACTION_EDIT);
        intent.setType("vnd.android.cursor.item/event");
        intent.putExtra("beginTime", cal.getTimeInMillis());
        intent.putExtra("allDay", true);
        intent.putExtra("rrule", "FREQ=YEARLY");
        intent.putExtra("endTime", cal.getTimeInMillis()+60*60*1000);
        intent.putExtra("title", "A Test Event from android app");
        startActivity(intent);
        }

Hope it would help.....

Milan Shukla
  • 1,602
  • 18
  • 16
  • about the Build.VERSION.SDK_INT > 14, how can I add a default reminder for 60 min and how can I get the Id of the reminder? Thanks – user1796624 Jul 02 '13 at 13:17
  • Hi, I was wondering if its possible to modify the screen that shows the editable calendar fields (like change how some of the views look)? – Yulric Sequeira Aug 08 '13 at 16:10
  • @user1950599 Definitely not. Intent starts an Activity from another application and the only interaction with it is the data you send via the intent. – Pijusn Jan 18 '15 at 13:56
41

As of Android version 4.0 official APIs and intents are available to interact with the available calendar providers.

tobsen
  • 5,328
  • 3
  • 34
  • 51
16

how do I programmatically add an event to the user's calendar?

Which calendar?

Is there a common API they all share?

No, no more than there is a "common API they all share" for Windows calendar apps. There are some common data formats (e.g., iCalendar) and Internet protocols (e.g., CalDAV), but no common API. Some calendar apps don't even offer an API.

If there are specific calendar applications you wish to integrate with, contact their developers and determine if they offer an API. So, for example, the Calendar application from the Android open source project, that Mayra cites, offers no documented and supported APIs. Google has even explicitly told developers to not use the techniques outlined in the tutorial Mayra cites.

Another option is for you to add events to the Internet calendar in question. For example, the best way to add events to the Calendar application from the Android open source project is to add the event to the user's Google Calendar via the appropriate GData APIs.


UPDATE

Android 4.0 (API Level 14) added a CalendarContract ContentProvider.

CommonsWare
  • 986,068
  • 189
  • 2,389
  • 2,491
  • 7
    We don't want to target a specific calendar - we just want to be able to add events to whatever calendar the user is using, just as a convenience to the user. Our app provides an interface to a website that organizes professional meetings and conferences. So if someone signs up for one it would be nice to pop it into their calendar. – Peter Nelson Sep 15 '10 at 23:26
  • I think that using the unofficial api is currently the best way to do that, even if Google discourages that. – fhucho Sep 15 '10 at 23:51
  • 4
    @Peter Nelson: "We don't want to target a specific calendar - we just want to be able to add events to whatever calendar the user is using, just as a convenience to the user." -- you can't do that on Android any more than you can do that on Windows. On neither platform do you know "whatever calendar the user is using", and on neither platform is there a universal API for working with such a calendar application. – CommonsWare Sep 15 '10 at 23:55
  • 25
    I don't know why you keep comparing it to Windows - Everybody I know uses their phone to organize their schedules and appointments - I don't know anyone who does that on their PC - maybe it's a generational thing. But I get that Android can't do that. Thanks. – Peter Nelson Sep 16 '10 at 00:32
  • 6
    @Peter Nelson: I keep comparing it to Windows because people make the same assumptions. A lot of developers think they can "add events to whatever calendar the user is using" on Windows, because they think everyone uses Outlook, and hence there is only one "whatever calendar". – CommonsWare Sep 16 '10 at 00:40
  • @CommonsWare "Which calendar?" The main Android phone calendar, which any Android phone has. – Yar May 25 '11 at 18:41
  • 2
    @Yar: "The main Android phone calendar, which any Android phone has." -- except for all the Android devices that do not have that app. For example, many HTC devices do not have that app, but rather have their own calendar app, such as the HTC DROID Incredible six inches to my left. Device manufacturers are welcome to replace the calendar app -- or just about any other app -- with their own implementation. – CommonsWare May 25 '11 at 22:15
  • @CommonsWare "the Calendar application from the Android open source project, that Mayra cites". It seems Mayra deleted her comment? – Jose_GD Jul 30 '13 at 19:17
  • @CommonsWare I am trying to add event in the Google calendar through Calendar Contracts and my device version is greater than 14.But still my event gets disappeared from the calendar after some seconds.This is my issue link : http://stackoverflow.com/questions/39568162/google-calendar-event-hides-after-some-time Please help me. – Harsh Parikh Oct 15 '16 at 09:44
10

Try this ,

   Calendar beginTime = Calendar.getInstance();
    beginTime.set(yearInt, monthInt - 1, dayInt, 7, 30);



    ContentValues l_event = new ContentValues();
    l_event.put("calendar_id", CalIds[0]);
    l_event.put("title", "event");
    l_event.put("description",  "This is test event");
    l_event.put("eventLocation", "School");
    l_event.put("dtstart", beginTime.getTimeInMillis());
    l_event.put("dtend", beginTime.getTimeInMillis());
    l_event.put("allDay", 0);
    l_event.put("rrule", "FREQ=YEARLY");
    // status: 0~ tentative; 1~ confirmed; 2~ canceled
    // l_event.put("eventStatus", 1);

    l_event.put("eventTimezone", "India");
    Uri l_eventUri;
    if (Build.VERSION.SDK_INT >= 8) {
        l_eventUri = Uri.parse("content://com.android.calendar/events");
    } else {
        l_eventUri = Uri.parse("content://calendar/events");
    }
    Uri l_uri = MainActivity.this.getContentResolver()
            .insert(l_eventUri, l_event);
Arun Antoney
  • 4,292
  • 2
  • 20
  • 26
8

Just in case if someone needs this for Xamarin in c#:

        Intent intent = new Intent(Intent.ActionInsert);
        intent.SetData(Android.Provider.CalendarContract.Events.ContentUri);
        intent.PutExtra(Android.Provider.CalendarContract.ExtraEventBeginTime, Utils.Tools.CurrentTimeMillis(game.Date));
        intent.PutExtra(Android.Provider.CalendarContract.EventsColumns.AllDay, false);
        intent.PutExtra(Android.Provider.CalendarContract.EventsColumns.EventLocation, "Location");
        intent.PutExtra(Android.Provider.CalendarContract.EventsColumns.Description, "Description");
        intent.PutExtra(Android.Provider.CalendarContract.ExtraEventEndTime, Utils.Tools.CurrentTimeMillis(game.Date.AddHours(2)));
        intent.PutExtra(Android.Provider.CalendarContract.EventsColumns.Title, "Title");
        StartActivity(intent);

Helper Functions:

    private static readonly DateTime Jan1st1970 = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);

    public static long CurrentTimeMillis(DateTime date)
    {
        return (long)(date.ToUniversalTime() - Jan1st1970).TotalMilliseconds;
    }
dotsa
  • 911
  • 1
  • 11
  • 15
7

Google calendar is the "native" calendar app. As far as I know, all phones come with a version of it installed, and the default SDK provides a version.

You might check out this tutorial for working with it.

Rüdiger Hanke
  • 6,215
  • 2
  • 38
  • 45
Cheryl Simon
  • 46,552
  • 15
  • 93
  • 82
4

if you have a given Date string with date and time .

for e.g String givenDateString = pojoModel.getDate()/* Format dd-MMM-yyyy hh:mm:ss */

use the following code to add an event with date and time to the calendar

Calendar cal = Calendar.getInstance();
cal.setTime(new SimpleDateFormat("dd-MMM-yyyy hh:mm:ss").parse(givenDateString));
Intent intent = new Intent(Intent.ACTION_EDIT);
intent.setType("vnd.android.cursor.item/event");
intent.putExtra("beginTime", cal.getTimeInMillis());
intent.putExtra("allDay", false);
intent.putExtra("rrule", "FREQ=YEARLY");
intent.putExtra("endTime",cal.getTimeInMillis() + 60 * 60 * 1000);
intent.putExtra("title", " Test Title");
startActivity(intent);
TNR
  • 5,839
  • 3
  • 33
  • 62
Arun
  • 2,800
  • 23
  • 13
3

you have to add flag:

intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

or you will cause error with:

startActivity() from outside of an Activity context requires the FLAG_ACTIVITY_NEW_TASK

Gabriele Mariotti
  • 320,139
  • 94
  • 887
  • 841
john vuong
  • 245
  • 2
  • 5
0

Here is the Kotlin version for adding event to calendar :

            val intent = Intent(Intent.ACTION_EDIT)
            intent.type = "vnd.android.cursor.item/event"
            intent.putExtra(CalendarContract.EXTRA_EVENT_BEGIN_TIME, startTime)
            intent.putExtra(CalendarContract.EXTRA_EVENT_END_TIME, endTime)
            intent.putExtra(CalendarContract.EXTRA_EVENT_ALL_DAY, false)
            intent.putExtra(CalendarContract.Events.TITLE, mTitle)
            startActivity(intent)
Mahdi Giveie
  • 630
  • 1
  • 8
  • 25
0

Android provides mainly two approaches to work on calendar events. One is using Calendar Provider and the other one is handing off it to the system Calendar app.

Calendar Provider provides us all the functionalities, including inserting, querying, updating and deleting existing calendar events. However, the steps are tedious and must require user’s runtime permissions (android.permission.READ_CALENDAR and android.permission.WRITE_CALENDAR) to read and write the sensitive calendar information. It is easy to make a mistake with this approach.

enter image description here

Google officially recommends developers use the second approach, i.e. handing off all the calendar operations to the system Calendar app by using Intent. The calendar app is opened right after requested by our app

Inserting new calendar even

    val startMillis: Long = Calendar.getInstance().run {
    set(2012, 0, 19, 7, 30)
    timeInMillis
}
val endMillis: Long = Calendar.getInstance().run {
    set(2012, 0, 19, 8, 30)
    timeInMillis
}
val intent = Intent(Intent.ACTION_INSERT)
        .setData(CalendarContract.Events.CONTENT_URI)
        .putExtra(CalendarContract.EXTRA_EVENT_BEGIN_TIME, startMillis)
        .putExtra(CalendarContract.EXTRA_EVENT_END_TIME, endMillis)
        .putExtra(CalendarContract.Events.TITLE, "Yoga")
        .putExtra(CalendarContract.Events.DESCRIPTION, "Group class")
        .putExtra(CalendarContract.Events.EVENT_LOCATION, "The gym")
        .putExtra(CalendarContract.Events.AVAILABILITY, CalendarContract.Events.AVAILABILITY_BUSY)
        .putExtra(Intent.EXTRA_EMAIL, "rowan@example.com,trevor@example.com")
startActivity(intent)

Following activity is opend

enter image description here

Rahul Devanavar
  • 3,917
  • 4
  • 32
  • 61