Xamarin:在将事件添加到android中的日历之前检查事件是否存在

时间:2016-08-25 07:12:48

标签: c# xamarin calendar xamarin.forms

我正在使用xamarin表单将事件添加到android平台的本机日历中。我已经创建了依赖服务来跨平台添加事件。我能够添加一个事件,但在添加任何事件之前,我想应用一个检查来限制是否存在任何具有相同唯一标识符的事件,然后它不应该允许添加该事件。

我尝试this但是没有用,因为我在Android平台上找不到xamarin中的任何Cursor类。

1 个答案:

答案 0 :(得分:1)

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
  • 投影 - 要返回的列
  • 开始 - 自纪元以来以UTC毫秒查询的时间范围的开始
  • end - 自纪元以来以UTC millis查询的时间范围的结束

提供整个教程和分步说明here。 阅读ContentResolver here

对于 iOS ,您必须使用 EventKit

要按照其ID检索事件,请使用EventFromIdentifier上的EventStore方法,并将从事件中提取的EventIdentifier传递给它:

var mySavedEvent = App.Current.EventStore.EventFromIdentifier (newEvent.EventIdentifier);

要搜索日历活动,您必须通过NSPredicate上的PredicateForEvents方法创建EventStore对象。 NSPredicate是iOS用于查找匹配项的查询数据对象:

NSPredicate query = App.Current.EventStore.PredicateForEvents (startDate, endDate, null);

第三个​​参数是要查询的日历,要使用所有日历,请传递null。

创建NSPredicate后,在EventStore上使用EventsMatching方法,执行查询:

EKCalendarItem[] events = App.Current.EventStore.EventsMatching (query);

完整的教程可用here,样本外观here

相关问题