How to add calendar events in Android?

Viewed 218091

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.

12 Answers

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)

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

Related