以编程方式将事件添加到日历

时间:2019-04-16 11:34:16

标签: android events calendar android-contentresolver

我开发了事件管理器。有些事件具有开始和结束的日期/时间。 我需要抓住机会将应用内事件插入到Android日历中。

这是我写的代码:

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)

此代码可在Android 5.0设备上完美运行(事件出现在日历应用中),但不适用于7.0设备。授予WRITE_CALENDARREAD_CALENDAR权限。

我的代码有什么问题?为什么在Android 7.0上不起作用?

1 个答案:

答案 0 :(得分:0)

我建议您使用intent继续使用Android的官方方式,建议您这样做,因为不需要权限检查。

跟随:

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)