2

I develop event manager. There are events with date/time of start and end. I need to implement opportunity to insert my in-app events to the android calendar.

Here is code I wrote:

val startMillis: Long = 1555406400000
    val endMillis: Long = 1555499400000
    val name = "Event"
    val description = "Awesome event"
    val allDay = false

    val values = ContentValues().apply {
      put(CalendarContract.Events.DTSTART, startMillis)
      put(CalendarContract.Events.DTEND, endMillis)
      put(CalendarContract.Events.TITLE, name)
      put(CalendarContract.Events.DESCRIPTION, description)
      put(CalendarContract.Events.ALL_DAY, allDay)
      put(CalendarContract.Events.CALENDAR_ID, 3) //Don't know why `3`, just copied from some example from inthernet
      put(CalendarContract.Events.EVENT_TIMEZONE, ZonedDateTime.now().zone.id)
    }

    val contentUri = CalendarContract.Events.CONTENT_URI
    activity.contentResolver.insert(contentUri, values)

This code works perfectly on the Android 5.0 device (Event is appears in the calendar app), but doesn't work on the 7.0 device. WRITE_CALENDAR and READ_CALENDAR permissions are granted.

Whats wrong with my code? Why it doesn't works on the Android 7.0?

P. Ilyin
  • 761
  • 10
  • 28

1 Answers1

0

I would suggest to go ahead with Android's official way using intent, recommended since no permission check required.

Followed:

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)
Faisal
  • 1,332
  • 2
  • 13
  • 29