我正在使用xamarin表单将事件添加到android平台的 native 日历中。我已经制作了依赖服务来跨平台添加事件。我可以添加事件,但在添加任何事件之前,我想应用检查来限制是否存在具有相同唯一标识符的任何事件,则不应允许添加该事件。
我试过this但没有成功,因为我在 Android 平台上的 xamarin 中找不到任何 Cursor
类。
最佳答案
在 Android 上,您需要执行以下操作才能使用新 API 从日历中获取数据。
您需要权限android.permisson.READ_CALENDAR
使用CalendarContract
类与日历数据交互。此类提供了应用程序在与日历提供程序交互时可以使用的数据模型。
枚举已在日历应用程序中注册的日历。为此,我们可以调用 ManagedQuery方法。至少,我们需要指定日历的内容 Uri 以及我们想要返回的列;该列规范称为投影。调用 ManagedQuery
允许我们查询内容提供程序的数据(例如日历提供程序),并返回包含查询结果的 Cursor。
var calendarsUri = CalendarContract.Calendars.ContentUri;
指定投影:
string[] calendarsProjection = {
CalendarContract.Calendars.InterfaceConsts.Id,
CalendarContract.Calendars.InterfaceConsts.CalendarDisplayName,
CalendarContract.Calendars.InterfaceConsts.AccountName,
, CalendarContract.Events.InterfaceConsts.Title
, CalendarContract.Events.InterfaceConsts.Dtstart
, CalendarContract.Events.InterfaceConsts.Dtend
};
您可以传入更多参数而不是 null。查看其他可用参数here .
var cursor = ManagedQuery (calendarsUri, calendarsProjection, null, null, null);
托管查询已弃用,最好使用 ContentResolver
。
var cursor = context.ContentResolver.Query(calendarsUri, calendarsProjection, null, null, null);
带有日期过滤器:
var selection = "((dtstart <= ?) AND (dtend >= ?))";
var selectionArgs = new string[] { startString, endString };
Forms.Context.ApplicationContext.ContentResolver.Query(calendarsUri, calendarsProjection, selection, selectionArgs, null);
或
var ctx = Forms.Context;
var cursor = ctx.ApplicationContext.ContentResolver.Query(calendarsUri, calendarsProjection, null, null, null);
Query的参数是:
- cr - 用于查询的 ContentResolver
- 投影 - 要返回的列
- begin - 从纪元开始查询的时间范围(以 UTC 毫秒为单位)
- end - 自纪元以来查询的时间范围结束时间(以 UTC 毫秒为单位)
提供了整个教程和分步说明 here 。
了解 ContentResolver
here .
对于iOS,您必须使用EventKit。
要按 ID 检索事件,请使用 EventStore
上的 EventFromIdentifier
方法,并向其传递从事件中提取的 EventIdentifier
:
var mySavedEvent = App.Current.EventStore.EventFromIdentifier (newEvent.EventIdentifier);
要搜索日历事件,您必须通过 EventStore
上的 PredicateForEvents
方法创建一个 NSPredicate
对象。 NSPredicate
是 iOS 用于定位匹配项的查询数据对象:
NSPredicate query = App.Current.EventStore.PredicateForEvents (startDate, endDate, null);
第三个参数是要查询的日历,要使用所有日历,则传递null。
创建 NSPredicate 后,使用 EventStore 上的 EventsMatching 方法,执行查询:
EKCalendarItem[] events = App.Current.EventStore.EventsMatching (query);
关于c# - Xamarin:在将事件添加到 Android 日历之前检查事件是否存在,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39138894/