最近要做一个日历提醒,使用户可以每天收到提醒,其中遇到一个重复的问题
参考了添加日历中的RRULE 设定
if (context == null) {
return null
}
val calId = checkAndAddCalendarAccount(context) //获取日历账户的id
if (calId < 0) { //获取账户id失败直接返回,添加日历事件失败
KLog.a("addCalendarEvent fail $calId")
return null
}
//添加日历事件
val mCalendar: Calendar = Calendar.getInstance()
mCalendar.timeInMillis = reminderTime //设置开始时间
val start: Long = mCalendar.time.time
mCalendar.timeInMillis = start //设置终止时间,开始时间加10分钟
val end: Long = mCalendar.time.time + 10 * 60 * 1000
val event = ContentValues()
event.put("title", title)
event.put("description", description)
event.put("calendar_id", calId) //插入账户的id
event.put(CalendarContract.Events.DTSTART, start)
event.put(CalendarContract.Events.DTEND, end)
//设置每天重复
event.put(CalendarContract.Events.RRULE, "FREQ=DAILY;INTERVAL=1")
event.put(CalendarContract.Events.HAS_ALARM, 1) //设置有闹钟提醒
event.put(CalendarContract.Events.EVENT_TIMEZONE, "Asia/Shanghai") //这个是时区,必须有
val newEvent: Uri =
context.contentResolver.insert(Uri.parse(CALENDER_EVENT_URL), event)
?: //添加日历事件失败直接返回
return null //添加事件
//事件提醒的设定
val values = ContentValues()
values.put(CalendarContract.Reminders.EVENT_ID, ContentUris.parseId(newEvent))
values.put(CalendarContract.Reminders.MINUTES, 10) // 提前previousDate天有提醒
values.put(
CalendarContract.Reminders.METHOD,
CalendarContract.Reminders.METHOD_ALERT
)
val uri: Uri? =
context.contentResolver.insert(Uri.parse(CALENDER_REMINDER_URL), values)
添加账户的代码如下
/**
* 检查是否已经添加了日历账户,如果没有添加先添加一个日历账户再查询
* 获取账户成功返回账户id,否则返回-1
*/
private fun checkAndAddCalendarAccount(context: Context): Int {
val oldId = checkCalendarAccount(context)
return if (oldId >= 0) {
oldId
} else {
val addId = addCalendarAccount(context)
if (addId >= 0) {
checkCalendarAccount(context)
} else {
-1
}
}
}
删除日历行程
if (context == null) {
return false
}
val eventCursor: Cursor? = context.contentResolver
.query(Uri.parse(CALENDER_EVENT_URL), null, null, null, null)
eventCursor.use { eventCursor ->
if (eventCursor == null) { //查询返回空值
return false
}
if (eventCursor.count > 0) {
//遍历所有事件,找到title跟需要查询的title一样的项
eventCursor.moveToFirst()
while (!eventCursor.isAfterLast) {
val eventTitle: String =
eventCursor.getString(eventCursor.getColumnIndex("title"))
if (!TextUtils.isEmpty(title) && title == eventTitle) {
val id: Int =
eventCursor.getInt(eventCursor.getColumnIndex(CalendarContract.Calendars._ID)) //取得id
val deleteUri: Uri =
ContentUris.withAppendedId(
Uri.parse(CALENDER_EVENT_URL),
id.toLong()
)
val rows: Int =
context.contentResolver.delete(deleteUri, null, null)
KLog.a("deleteCalendarEvent success $rows")
MMKVSystemConfig.putBoolean(Constant.SET_CALENDAR, rows == -1)
if (rows == -1) { //事件删除失败
return false
}
}
eventCursor.moveToNext()
}
}
参考 https://www.jianshu.com/p/b98a543280c3