我正在尝试将事件添加到Android上的日历中。添加工作正常,但每次调用add事件方法时,都会创建重复项。我尝试更新事件,并删除具有特定标题的所有事件,但没有成功。
我的导入方法:
public static boolean importToCalendar(@NonNull Activity activity, CalendarEvent calendarEvent) {
if (ActivityCompat.checkSelfPermission(activity, Manifest.permission.WRITE_CALENDAR)
!= PackageManager.PERMISSION_GRANTED)
return false;
removeExistingEvent(activity, calendarEvent);
ContentValues event = new ContentValues();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M)
event.put(Events.CALENDAR_ID, 3);
else
event.put(Events.CALENDAR_ID, 1);
event.put(Events.TITLE, calendarEvent.getTitle());
event.put(Events.DESCRIPTION, calendarEvent.getDescription());
event.put(Events.DTSTART, calendarEvent.getStartTime());
event.put(Events.DTEND, calendarEvent.getEndTime());
event.put(Events.STATUS, calendarEvent.getEventStatus());
event.put(Events.HAS_ALARM, calendarEvent.getHasAlarm());
event.put(Events.EVENT_TIMEZONE, TimeZone.getDefault().getID());
Uri uri = activity.getContentResolver().insert(Events.CONTENT_URI, event);
Log.d("calendar: ", "inserted " + uri);
// long eventId = getLastEventId(uri);
return true;
}
其中removeExistingEvent是:
public static void removeExistingEvent(@NonNull Activity activity, CalendarEvent calendarEvent) {
String[] proj =
new String[]{
CalendarContract.Instances._ID,
CalendarContract.Instances.BEGIN,
CalendarContract.Instances.END,
CalendarContract.Instances.EVENT_ID};
ContentResolver contentResolver = activity.getContentResolver();
Cursor cursor = CalendarContract.Instances.query(
contentResolver,
proj,
calendarEvent.getStartTime(),
calendarEvent.getEndTime(),
calendarEvent.getTitle());
while (cursor.moveToNext()) {
long id = cursor.getLong(cursor.getColumnIndex("_id"));
Uri eventUri = ContentUris.withAppendedId(Events.CONTENT_URI, id);
contentResolver.delete(eventUri, null, null);
Log.d("calendar: ", "deleted" + id);
}
}
日志说:
W / ContentResolver:无法获取以下内容的类型:content://com.android.calendar(未知网址内容://com.android.calendar) 06-15 12:03:22.872 9934-9934 / com.ptr D / calendar :: deleted482 06-15 12:03:22.899 6312-6325 / com.android.providers.calendar W / ContentResolver:无法获取类型:content://com.android.calendar(未知URL内容://com.android.calendar ) 06-15 12:03:22.918 9934-9934 / com.ptr D / calendar :: inserted content://com.android.calendar/events/299
非常感谢任何帮助。
答案 0 :(得分:0)
尝试通过eventId删除,而不是按标题删除。您可以在Events: delete。
中尝试service.events().delete(calendarId='primary', eventId='eventId').execute()