How to add calendar events in Android?
Asked Answered
C

13

167

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.

Chide answered 15/9, 2010 at 21:29 Comment(2)
You should probably accept oriharel's answer since he provides the code to accomplish your task.Whodunit
@SumitSharma your link seems to no longer work -- and seems pretty suspect with the automatic install dialog.Hilly
H
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.

Hispaniola answered 15/9, 2010 at 23:13 Comment(9)
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.Chide
I think that using the unofficial api is currently the best way to do that, even if Google discourages that.Fossorial
@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.Hispaniola
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.Chide
@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".Hispaniola
@Hispaniola "Which calendar?" The main Android phone calendar, which any Android phone has.Lyrism
@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.Hispaniola
@Hispaniola "the Calendar application from the Android open source project, that Mayra cites". It seems Mayra deleted her comment?Subjective
@Hispaniola 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 : #39568662 Please help me.Knoxville
C
300

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);
Cathleencathlene answered 2/12, 2010 at 14:43 Comment(16)
I like this solution a lot. Mainly because it pushes the user to select his/her own calendar (if he has more than one).Shreeves
Thanks. Does this also work with sense? No funky nonsense with HTC overriding calendars, etc?Limicolous
Using the code above, can I add a custom tone for the cal event notification?Porphyria
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)Pretor
how to make this compatible for android 2.2?Enforce
This is a great answer! Works on my app. One Question: Will this work on any device with a calendar app installed?Kloster
@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 fileValentine
I want to start my app from calendar event, please help me how can I add a uri scheme to calendar eventRanitta
You should use .setData(CalendarContract.Events.CONTENT_URI) instead of setType, because with setType(string) it will crash on some devices!Colner
how do you also add location? @CathleencathleneEvanston
@Pretor try 5L * 60L * 60L * 1000LSampler
Full tutorial here: code.tutsplus.com/tutorials/… It's better to use constants for avoiding typos ;)Kopeck
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.Operation
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.Symer
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".Massimiliano
permissions are not necessaryTorrent
K
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", "[email protected]");// 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;

}
Kelda answered 25/4, 2012 at 6:12 Comment(13)
this code is not working for me can anybody please provide me the proper solution for same issue?Cadmar
01-11 16:06:01.928: E/AndroidRuntime(24027): java.lang.IllegalArgumentException: Event values must include an eventTimezoneCadmar
I added event.put("eventTimezone", "UTC/GMT +2:00") and eliminated event.put("visibility", 3) and event.put("transparency", 0) and it works wellJamal
Maybe get timezone error. I add this and its works eventValues.put("eventTimezone", TimeZone.getDefault().getID());Parrish
I am getting android.database.sqlite.SQLiteException at line Uri reminderUri = curActivity.getApplicationContext().getContentResolver().insert(Uri.parse(reminderUriString), reminderValues);Jobyna
This code not working for me. It always return eventId but calander app not showing that event to calendar. Please help me.Reina
@Kelda 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);Overtop
I am also getting eventId but calander app not showing that event in calendar.Amoretto
My data goes into birthday instead of events. any solution for that? @Amitabha BiswasBlaubok
Solved the problem #44175199Blaubok
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. @AmitabhaBiswasBlaubok
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); @AmitabhaBiswasBlaubok
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?Slavery
E
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, "[email protected],[email protected]");
         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.....

Equiangular answered 1/6, 2013 at 10:36 Comment(3)
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? ThanksYuletide
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)?Sosthena
@user1950599 Definitely not. Intent starts an Activity from another application and the only interaction with it is the data you send via the intent.Infirmary
D
42

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

Debase answered 9/1, 2012 at 18:45 Comment(3)
Really usefull comment, can't Stress this one enough :)Landside
Perhaps you can provide some code to go along with the link-only answer?Whodunit
no calendar event color different scheme over there?Fantan
H
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.

Hispaniola answered 15/9, 2010 at 23:13 Comment(9)
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.Chide
I think that using the unofficial api is currently the best way to do that, even if Google discourages that.Fossorial
@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.Hispaniola
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.Chide
@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".Hispaniola
@Hispaniola "Which calendar?" The main Android phone calendar, which any Android phone has.Lyrism
@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.Hispaniola
@Hispaniola "the Calendar application from the Android open source project, that Mayra cites". It seems Mayra deleted her comment?Subjective
@Hispaniola 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 : #39568662 Please help me.Knoxville
F
11

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);
Frizzy answered 31/1, 2014 at 13:30 Comment(1)
nobody say something for this?Fantan
H
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;
    }
Hyder answered 28/9, 2014 at 18:41 Comment(0)
P
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.

Phonation answered 15/9, 2010 at 21:59 Comment(0)
D
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);
Darter answered 30/3, 2014 at 16:59 Comment(0)
L
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

Lowney answered 25/1, 2015 at 18:21 Comment(0)
I
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)
Inversion answered 10/3, 2021 at 5:37 Comment(0)
S
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, "[email protected],[email protected]")
startActivity(intent)

Following activity is opend

enter image description here

Stour answered 18/8, 2021 at 7:59 Comment(0)
C
0
Calendar beginTime = Calendar.getInstance();
beginTime.set(2012, 0, 19, 7, 30);
Calendar endTime = Calendar.getInstance();
endTime.set(2012, 0, 19, 8, 30);
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, "[email protected],[email protected]");
startActivity(intent);

this is official tutorial from :

https://developer.android.com/guide/topics/providers/calendar-provider?hl=id#intent-insert

it work!

Chausses answered 12/12, 2023 at 3:30 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.