Android实现系统日历同步日程
程序员文章站
2022-06-25 18:54:21
本文实例为大家分享了android实现系统日历同步日程的具体代码,供大家参考,具体内容如下1、权限
本文实例为大家分享了android实现系统日历同步日程的具体代码,供大家参考,具体内容如下
1、权限
<uses-permission android:name="android.permission.write_calendar" /> <uses-permission android:name="android.permission.read_calendar" />
2、动态权限activity中
if (contextcompat.checkselfpermission(this, manifest.permission.write_calendar) != packagemanager.permission_granted) { activitycompat.requestpermissions(this, new string[]{manifest.permission.write_calendar, manifest.permission.read_calendar}, 1); }
3、使用
string tiptime = "2021-04-25 12:00"; long start = timeutils.stringtolong(tiptime ,"yyyy-mm-dd hh:mm"); long end = start + 60 * 60 * 1000l; logutil.d("start:" + start); logutil.d("end:" + end); string[] split = tiptime.split(" "); string[] datestr = split[0].split("-"); int month = integer.parseint(datestr[1]); int day = integer.parseint(datestr[2]); string until = "20221231t235959z";//截止时间:2022年12月31日23点59分59秒 string mrule = ""; switch (mrepeattype) { case 1://不重复 mrule = null; break; case 2://按年重复(每年的某月某日) mrule = "freq=yearly;until=" + until + ";wkst=su;bymonth=" + month + ";bymonthday=" + day; break; case 3://按月重复(每月的某天) mrule = "freq=monthly;until=" + until + ";wkst=su;bymonthday=" + day; break; case 4://按周重复 string date = split[0]; string week = timeutils.getweek(date); switch (week) { case "周日": mrule = "freq=weekly;until=" + until + ";wkst=su;byday=su"; break; case "周一": mrule = "freq=weekly;until=" + until + ";wkst=su;byday=mo"; break; case "周二": mrule = "freq=weekly;until=" + until + ";wkst=su;byday=tu"; break; case "周三": mrule = "freq=weekly;until=" + until + ";wkst=su;byday=we"; break; case "周四": mrule = "freq=weekly;until=" + until + ";wkst=su;byday=th"; break; case "周五": mrule = "freq=weekly;until=" + until + ";wkst=su;byday=fr"; break; case "周六": mrule = "freq=weekly;until=" + until + ";wkst=su;byday=sa"; break; } break; case 5://按天(每天) mrule = "freq=daily;until=" + until; break; case 6://自定义周几重复,可多选 mrule = "freq=weekly;until=" + until + ";wkst=su;byday="; string[] weeks = mselectedweekstr.split(","); for (int i = 0; i < weeks.length; i++) { if (weeks[i].equals("周日")) { mrule += "su,"; } else if (weeks[i].equals("周一")) { mrule += "mo,"; } else if (weeks[i].equals("周二")) { mrule += "tu,"; } else if (weeks[i].equals("周三")) { mrule += "we,"; } else if (weeks[i].equals("周四")) { mrule += "th,"; } else if (weeks[i].equals("周五")) { mrule += "fr,"; } else if (weeks[i].equals("周六")) { mrule += "sa,"; } } if (mrule.endswith(",")) { mrule.substring(0, mrule.length() - 1); } break; } logutil.d("mrule:" + mrule); calendarevent calendarevent = new calendarevent( mcontent, mcontent, "", start, end, 0, mrule ); // 添加事件 int addresult = calendarprovidermanager.addcalendarevent(addscheduleactivity.this, calendarevent); if (addresult == 0) { toastutil.showshorttoast("插入成功"); } else if (addresult == -1) { toastutil.showshorttoast("插入失败"); } else if (addresult == -2) { toastutil.showshorttoast("没有权限"); }
3、时间转换方法
public static long stringtolong(string strtime, string formattype) { date date = null; // string类型转成date类型 try { date = stringtodate(strtime, formattype); } catch (exception e) { e.printstacktrace(); } if (date == null) { return 0; } else { long currenttime = datetolong(date); // date类型转成long类型 return currenttime; } } public static date stringtodate(string strtime, string formattype) { simpledateformat formatter = new simpledateformat(formattype); date date = null; try { date = formatter.parse(strtime); } catch (parseexception e) { e.printstacktrace(); } return date; } // date要转换的date类型的时间 public static long datetolong(date date) { return date.gettime(); }
4、calendarprovidermanager 类
import android.content.contenturis; import android.content.contentvalues; import android.content.context; import android.content.intent; import android.content.pm.packagemanager; import android.database.cursor; import android.graphics.color; import android.net.uri; import android.os.build; import android.provider.calendarcontract; import calendarprovider.util; import java.util.arraylist; import java.util.list; import java.util.timezone; import static com.kyle.calendarprovider.util.checkcontextnull; /** * 系统日历工具 */ public class calendarprovidermanager { private static stringbuilder builder = new stringbuilder(); /** * tip: 要向系统日历插入事件,前提系统中必须存在至少1个日历账户 ** / // ----------------------- 创建日历账户时账户名使用 --------------------------- private static string calendar_name = "testc"; private static string calendar_account_name = "test"; private static string calendar_display_name = "test的账户"; // ------------------------------- 日历账户 ----------------------------------- /** * 获取日历账户id(若没有则会自动创建一个) * * @return success: 日历账户id failed : -1 permission deny : -2 */ @suppresswarnings("weakeraccess") public static long obtaincalendaraccountid(context context) { long calid = checkcalendaraccount(context); if (calid >= 0) { return calid; } else { return createcalendaraccount(context); } } /** * 检查是否存在日历账户 * * @return 存在:日历账户id 不存在:-1 */ private static long checkcalendaraccount(context context) { try (cursor cursor = context.getcontentresolver().query(calendarcontract.calendars.content_uri, null, null, null, null)) { // 不存在日历账户 if (null == cursor) { return -1; } int count = cursor.getcount(); // 存在日历账户,获取第一个账户的id if (count > 0) { cursor.movetofirst(); return cursor.getint(cursor.getcolumnindex(calendarcontract.calendars._id)); } else { return -1; } } } /** * 创建一个新的日历账户 * * @return success:account id , create failed:-1 , permission deny:-2 */ private static long createcalendaraccount(context context) { // 系统日历表 uri uri = calendarcontract.calendars.content_uri; // 要创建的账户 uri accounturi; // 开始组装账户数据 contentvalues account = new contentvalues(); // 账户类型:本地 // 在添加账户时,如果账户类型不存在系统中,则可能该新增记录会被标记为脏数据而被删除 // 设置为account_type_local可以保证在不存在账户类型时,该新增数据不会被删除 account.put(calendarcontract.calendars.account_type, calendarcontract.account_type_local); // 日历在表中的名称 account.put(calendarcontract.calendars.name, calendar_name); // 日历账户的名称 account.put(calendarcontract.calendars.account_name, calendar_account_name); // 账户显示的名称 account.put(calendarcontract.calendars.calendar_display_name, calendar_display_name); // 日历的颜色 account.put(calendarcontract.calendars.calendar_color, color.parsecolor("#515bd4")); // 用户对此日历的获取使用权限等级 account.put(calendarcontract.calendars.calendar_access_level, calendarcontract.calendars.cal_access_owner); // 设置此日历可见 account.put(calendarcontract.calendars.visible, 1); // 日历时区 account.put(calendarcontract.calendars.calendar_time_zone, timezone.getdefault().getid()); // 可以修改日历时区 account.put(calendarcontract.calendars.can_modify_time_zone, 1); // 同步此日历到设备上 account.put(calendarcontract.calendars.sync_events, 1); // 拥有者的账户 account.put(calendarcontract.calendars.owner_account, calendar_account_name); // 可以响应事件 account.put(calendarcontract.calendars.can_organizer_respond, 1); // 单个事件设置的最大的提醒数 account.put(calendarcontract.calendars.max_reminders, 8); // 设置允许提醒的方式 account.put(calendarcontract.calendars.allowed_reminders, "0,1,2,3,4"); // 设置日历支持的可用性类型 account.put(calendarcontract.calendars.allowed_availability, "0,1,2"); // 设置日历允许的出席者类型 account.put(calendarcontract.calendars.allowed_attendee_types, "0,1,2"); /** * tip: 修改或添加account_name只能由sync_adapter调用 * 对uri设置calendarcontract.caller_is_syncadapter为true,即标记当前操作为sync_adapter操作 * 在设置calendarcontract.caller_is_syncadapter为true时,必须带上参数account_name和account_type(任意) **/ uri = uri.buildupon() .appendqueryparameter(calendarcontract.caller_is_syncadapter, "true") .appendqueryparameter(calendarcontract.calendars.account_name, calendar_account_name) .appendqueryparameter(calendarcontract.calendars.account_type, calendarcontract.calendars.calendar_location) .build(); if (build.version.sdk_int >= build.version_codes.m) { // 检查日历权限 if (packagemanager.permission_granted == context.checkselfpermission( "android.permission.write_calendar")) { accounturi = context.getcontentresolver().insert(uri, account); } else { return -2; } } else { accounturi = context.getcontentresolver().insert(uri, account); } return accounturi == null ? -1 : contenturis.parseid(accounturi); } /** * 删除创建的日历账户 * * @return -2: permission deny 0: no designated account 1: delete success */ public static int deletecalendaraccountbyname(context context) { checkcontextnull(context); int deletecount; uri uri = calendarcontract.calendars.content_uri; string selection = "((" + calendarcontract.calendars.account_name + " = ?) and (" + calendarcontract.calendars.account_type + " = ?))"; string[] selectionargs = new string[]{calendar_account_name, calendarcontract.account_type_local}; if (build.version.sdk_int >= build.version_codes.m) { if (packagemanager.permission_granted == context.checkselfpermission( "android.permission.write_calendar")) { deletecount = context.getcontentresolver().delete(uri, selection, selectionargs); } else { return -2; } } else { deletecount = context.getcontentresolver().delete(uri, selection, selectionargs); } return deletecount; } // ------------------------------- 添加日历事件 ----------------------------------- /** * 添加日历事件 * * @param calendarevent 日历事件(详细参数说明请参看{@link calendarevent}构造方法) * @return 0: success -1: failed -2: permission deny */ public static int addcalendarevent(context context, calendarevent calendarevent) { /** * tip: 插入一个新事件的规则: * 1. 必须包含calendar_id和dtstart字段 * 2. 必须包含event_timezone字段,使用timezone.getdefault().getid()方法获取默认时区 * 3. 对于非重复发生的事件,必须包含dtend字段 * 4. 对重复发生的事件,必须包含一个附加了rrule或rdate字段的duration字段 */ checkcontextnull(context); // 获取日历账户id,也就是要将事件插入到的账户 long calid = obtaincalendaraccountid(context); // 系统日历事件表 uri uri1 = calendarcontract.events.content_uri; // 创建的日历事件 uri eventuri; // 系统日历事件提醒表 uri uri2 = calendarcontract.reminders.content_uri; // 创建的日历事件提醒 uri reminderuri; // 开始组装事件数据 contentvalues event = new contentvalues(); // 事件要插入到的日历账户 event.put(calendarcontract.events.calendar_id, calid); setupevent(calendarevent, event); if (build.version.sdk_int >= build.version_codes.m) { // 判断权限 if (packagemanager.permission_granted == context.checkselfpermission( "android.permission.write_calendar")) { eventuri = context.getcontentresolver().insert(uri1, event); } else { return -2; } } else { eventuri = context.getcontentresolver().insert(uri1, event); } if (null == eventuri) { return -1; } if (-2 != calendarevent.getadvancetime()) { // 获取事件id long eventid = contenturis.parseid(eventuri); // 开始组装事件提醒数据 contentvalues reminders = new contentvalues(); // 此提醒所对应的事件id reminders.put(calendarcontract.reminders.event_id, eventid); // 设置提醒提前的时间(0:准时 -1:使用系统默认) reminders.put(calendarcontract.reminders.minutes, calendarevent.getadvancetime()); // 设置事件提醒方式为通知警报 reminders.put(calendarcontract.reminders.method, calendarcontract.reminders.method_alert); reminderuri = context.getcontentresolver().insert(uri2, reminders); if (null == reminderuri) { return -1; } } return 0; } // ------------------------------- 更新日历事件 ----------------------------------- /** * 更新指定id的日历事件 * * @param newcalendarevent 更新的日历事件 * @return -2: permission deny else success */ public static int updatecalendarevent(context context, long eventid, calendarevent newcalendarevent) { checkcontextnull(context); int updatedcount1; uri uri1 = calendarcontract.events.content_uri; uri uri2 = calendarcontract.reminders.content_uri; contentvalues event = new contentvalues(); setupevent(newcalendarevent, event); // 更新匹配条件 string selection1 = "(" + calendarcontract.events._id + " = ?)"; string[] selectionargs1 = new string[]{string.valueof(eventid)}; if (build.version.sdk_int >= build.version_codes.m) { if (packagemanager.permission_granted == context.checkselfpermission( "android.permission.write_calendar")) { updatedcount1 = context.getcontentresolver().update(uri1, event, selection1, selectionargs1); } else { return -2; } } else { updatedcount1 = context.getcontentresolver().update(uri1, event, selection1, selectionargs1); } contentvalues reminders = new contentvalues(); reminders.put(calendarcontract.reminders.minutes, newcalendarevent.getadvancetime()); reminders.put(calendarcontract.reminders.method, calendarcontract.reminders.method_alert); // 更新匹配条件 string selection2 = "(" + calendarcontract.reminders.event_id + " = ?)"; string[] selectionargs2 = new string[]{string.valueof(eventid)}; int updatedcount2 = context.getcontentresolver().update(uri2, reminders, selection2, selectionargs2); return (updatedcount1 + updatedcount2) / 2; } /** * 更新指定id事件的开始时间 * * @return if successfully returns 1 */ public static int updatecalendareventbegintime(context context, long eventid, long newbegintime) { checkcontextnull(context); uri uri = calendarcontract.events.content_uri; // 新的数据 contentvalues event = new contentvalues(); event.put(calendarcontract.events.dtstart, newbegintime); // 匹配条件 string selection = "(" + calendarcontract.events._id + " = ?)"; string[] selectionargs = new string[]{string.valueof(eventid)}; return context.getcontentresolver().update(uri, event, selection, selectionargs); } /** * 更新指定id事件的结束时间 * * @return if successfully returns 1 */ public static int updatecalendareventendtime(context context, long eventid, long newendtime) { checkcontextnull(context); uri uri = calendarcontract.events.content_uri; // 新的数据 contentvalues event = new contentvalues(); event.put(calendarcontract.events.dtend, newendtime); // 匹配条件 string selection = "(" + calendarcontract.events._id + " = ?)"; string[] selectionargs = new string[]{string.valueof(eventid)}; return context.getcontentresolver().update(uri, event, selection, selectionargs); } /** * 更新指定id事件的起始时间 * * @return if successfully returns 1 */ public static int updatecalendareventtime(context context, long eventid, long newbegintime, long newendtime) { checkcontextnull(context); uri uri = calendarcontract.events.content_uri; // 新的数据 contentvalues event = new contentvalues(); event.put(calendarcontract.events.dtstart, newbegintime); event.put(calendarcontract.events.dtend, newendtime); // 匹配条件 string selection = "(" + calendarcontract.events._id + " = ?)"; string[] selectionargs = new string[]{string.valueof(eventid)}; return context.getcontentresolver().update(uri, event, selection, selectionargs); } /** * 更新指定id事件的标题 * * @return if successfully returns 1 */ public static int updatecalendareventtitle(context context, long eventid, string newtitle) { checkcontextnull(context); uri uri = calendarcontract.events.content_uri; // 新的数据 contentvalues event = new contentvalues(); event.put(calendarcontract.events.title, newtitle); // 匹配条件 string selection = "(" + calendarcontract.events._id + " = ?)"; string[] selectionargs = new string[]{string.valueof(eventid)}; return context.getcontentresolver().update(uri, event, selection, selectionargs); } /** * 更新指定id事件的描述 * * @return if successfully returns 1 */ public static int updatecalendareventdes(context context, long eventid, string neweventdes) { checkcontextnull(context); uri uri = calendarcontract.events.content_uri; // 新的数据 contentvalues event = new contentvalues(); event.put(calendarcontract.events.description, neweventdes); // 匹配条件 string selection = "(" + calendarcontract.events._id + " = ?)"; string[] selectionargs = new string[]{string.valueof(eventid)}; return context.getcontentresolver().update(uri, event, selection, selectionargs); } /** * 更新指定id事件的地点 * * @return if successfully returns 1 */ public static int updatecalendareventlocation(context context, long eventid, string neweventlocation) { checkcontextnull(context); uri uri = calendarcontract.events.content_uri; // 新的数据 contentvalues event = new contentvalues(); event.put(calendarcontract.events.event_location, neweventlocation); // 匹配条件 string selection = "(" + calendarcontract.events._id + " = ?)"; string[] selectionargs = new string[]{string.valueof(eventid)}; return context.getcontentresolver().update(uri, event, selection, selectionargs); } /** * 更新指定id事件的标题和描述 * * @return if successfully returns 1 */ public static int updatecalendareventtitanddes(context context, long eventid, string neweventtitle, string neweventdes) { checkcontextnull(context); uri uri = calendarcontract.events.content_uri; // 新的数据 contentvalues event = new contentvalues(); event.put(calendarcontract.events.title, neweventtitle); event.put(calendarcontract.events.description, neweventdes); // 匹配条件 string selection = "(" + calendarcontract.events._id + " = ?)"; string[] selectionargs = new string[]{string.valueof(eventid)}; return context.getcontentresolver().update(uri, event, selection, selectionargs); } /** * 更新指定id事件的常用信息(标题、描述、地点) * * @return if successfully returns 1 */ public static int updatecalendareventcommoninfo(context context, long eventid, string neweventtitle, string neweventdes, string neweventlocation) { checkcontextnull(context); uri uri = calendarcontract.events.content_uri; // 新的数据 contentvalues event = new contentvalues(); event.put(calendarcontract.events.title, neweventtitle); event.put(calendarcontract.events.description, neweventdes); event.put(calendarcontract.events.event_location, neweventlocation); // 匹配条件 string selection = "(" + calendarcontract.events._id + " = ?)"; string[] selectionargs = new string[]{string.valueof(eventid)}; return context.getcontentresolver().update(uri, event, selection, selectionargs); } /** * 更新指定id事件的提醒方式 * * @return if successfully returns 1 */ private static int updatecalendareventreminder(context context, long eventid, long newadvancetime) { checkcontextnull(context); uri uri = calendarcontract.reminders.content_uri; contentvalues reminders = new contentvalues(); reminders.put(calendarcontract.reminders.minutes, newadvancetime); // 更新匹配条件 string selection2 = "(" + calendarcontract.reminders.event_id + " = ?)"; string[] selectionargs2 = new string[]{string.valueof(eventid)}; return context.getcontentresolver().update(uri, reminders, selection2, selectionargs2); } /** * 更新指定id事件的提醒重复规则 * * @return if successfully returns 1 */ private static int updatecalendareventrrule(context context, long eventid, string newrrule) { checkcontextnull(context); uri uri = calendarcontract.events.content_uri; // 新的数据 contentvalues event = new contentvalues(); event.put(calendarcontract.events.rrule, newrrule); // 匹配条件 string selection = "(" + calendarcontract.events._id + " = ?)"; string[] selectionargs = new string[]{string.valueof(eventid)}; return context.getcontentresolver().update(uri, event, selection, selectionargs); } // ------------------------------- 删除日历事件 ----------------------------------- /** * 删除日历事件 * * @param eventid 事件id * @return -2: permission deny else success */ public static int deletecalendarevent(context context, long eventid) { checkcontextnull(context); int deletedcount1; uri uri1 = calendarcontract.events.content_uri; uri uri2 = calendarcontract.reminders.content_uri; // 删除匹配条件 string selection = "(" + calendarcontract.events._id + " = ?)"; string[] selectionargs = new string[]{string.valueof(eventid)}; if (build.version.sdk_int >= build.version_codes.m) { if (packagemanager.permission_granted == context.checkselfpermission( "android.permission.write_calendar")) { deletedcount1 = context.getcontentresolver().delete(uri1, selection, selectionargs); } else { return -2; } } else { deletedcount1 = context.getcontentresolver().delete(uri1, selection, selectionargs); } // 删除匹配条件 string selection2 = "(" + calendarcontract.reminders.event_id + " = ?)"; string[] selectionargs2 = new string[]{string.valueof(eventid)}; int deletedcount2 = context.getcontentresolver().delete(uri2, selection2, selectionargs2); return (deletedcount1 + deletedcount2) / 2; } // ------------------------------- 查询日历事件 ----------------------------------- /** * 查询指定日历账户下的所有事件 * * @return if failed return null else return list<calendarevent> */ public static list<calendarevent> queryaccountevent(context context, long calid) { checkcontextnull(context); final string[] event_projection = new string[]{ calendarcontract.events.calendar_id, // 在表中的列索引0 calendarcontract.events.title, // 在表中的列索引1 calendarcontract.events.description, // 在表中的列索引2 calendarcontract.events.event_location, // 在表中的列索引3 calendarcontract.events.display_color, // 在表中的列索引4 calendarcontract.events.status, // 在表中的列索引5 calendarcontract.events.dtstart, // 在表中的列索引6 calendarcontract.events.dtend, // 在表中的列索引7 calendarcontract.events.duration, // 在表中的列索引8 calendarcontract.events.event_timezone, // 在表中的列索引9 calendarcontract.events.event_end_timezone, // 在表中的列索引10 calendarcontract.events.all_day, // 在表中的列索引11 calendarcontract.events.access_level, // 在表中的列索引12 calendarcontract.events.availability, // 在表中的列索引13 calendarcontract.events.has_alarm, // 在表中的列索引14 calendarcontract.events.rrule, // 在表中的列索引15 calendarcontract.events.rdate, // 在表中的列索引16 calendarcontract.events.has_attendee_data, // 在表中的列索引17 calendarcontract.events.last_date, // 在表中的列索引18 calendarcontract.events.organizer, // 在表中的列索引19 calendarcontract.events.is_organizer, // 在表中的列索引20 calendarcontract.events._id // 在表中的列索引21 }; // 事件匹配 uri uri = calendarcontract.events.content_uri; uri uri2 = calendarcontract.reminders.content_uri; string selection = "(" + calendarcontract.events.calendar_id + " = ?)"; string[] selectionargs = new string[]{string.valueof(calid)}; cursor cursor; if (build.version.sdk_int >= build.version_codes.m) { if (packagemanager.permission_granted == context.checkselfpermission( "android.permission.read_calendar")) { cursor = context.getcontentresolver().query(uri, event_projection, selection, selectionargs, null); } else { return null; } } else { cursor = context.getcontentresolver().query(uri, event_projection, selection, selectionargs, null); } if (null == cursor) { return null; } // 查询结果 list<calendarevent> result = new arraylist<>(); // 开始查询数据 if (cursor.movetofirst()) { do { calendarevent calendarevent = new calendarevent(); result.add(calendarevent); calendarevent.setid(cursor.getlong(cursor.getcolumnindex( calendarcontract.events._id))); calendarevent.setcalid(cursor.getlong(cursor.getcolumnindex( calendarcontract.events.calendar_id))); calendarevent.settitle(cursor.getstring(cursor.getcolumnindex( calendarcontract.events.title))); calendarevent.setdescription(cursor.getstring(cursor.getcolumnindex( calendarcontract.events.description))); calendarevent.seteventlocation(cursor.getstring(cursor.getcolumnindex( calendarcontract.events.event_location))); calendarevent.setdisplaycolor(cursor.getint(cursor.getcolumnindex( calendarcontract.events.display_color))); calendarevent.setstatus(cursor.getint(cursor.getcolumnindex( calendarcontract.events.status))); calendarevent.setstart(cursor.getlong(cursor.getcolumnindex( calendarcontract.events.dtstart))); calendarevent.setend(cursor.getlong(cursor.getcolumnindex( calendarcontract.events.dtend))); calendarevent.setduration(cursor.getstring(cursor.getcolumnindex( calendarcontract.events.duration))); calendarevent.seteventtimezone(cursor.getstring(cursor.getcolumnindex( calendarcontract.events.event_timezone))); calendarevent.seteventendtimezone(cursor.getstring(cursor.getcolumnindex( calendarcontract.events.event_end_timezone))); calendarevent.setallday(cursor.getint(cursor.getcolumnindex( calendarcontract.events.all_day))); calendarevent.setaccesslevel(cursor.getint(cursor.getcolumnindex( calendarcontract.events.access_level))); calendarevent.setavailability(cursor.getint(cursor.getcolumnindex( calendarcontract.events.availability))); calendarevent.sethasalarm(cursor.getint(cursor.getcolumnindex( calendarcontract.events.has_alarm))); calendarevent.setrrule(cursor.getstring(cursor.getcolumnindex( calendarcontract.events.rrule))); calendarevent.setrdate(cursor.getstring(cursor.getcolumnindex( calendarcontract.events.rdate))); calendarevent.sethasattendeedata(cursor.getint(cursor.getcolumnindex( calendarcontract.events.has_attendee_data))); calendarevent.setlastdate(cursor.getint(cursor.getcolumnindex( calendarcontract.events.last_date))); calendarevent.setorganizer(cursor.getstring(cursor.getcolumnindex( calendarcontract.events.organizer))); calendarevent.setisorganizer(cursor.getstring(cursor.getcolumnindex( calendarcontract.events.is_organizer))); // ----------------------- 开始查询事件提醒 ------------------------------ string[] reminder_projection = new string[]{ calendarcontract.reminders._id, // 在表中的列索引0 calendarcontract.reminders.event_id, // 在表中的列索引1 calendarcontract.reminders.minutes, // 在表中的列索引2 calendarcontract.reminders.method, // 在表中的列索引3 }; string selection2 = "(" + calendarcontract.reminders.event_id + " = ?)"; string[] selectionargs2 = new string[]{string.valueof(calendarevent.getid())}; try (cursor remindercursor = context.getcontentresolver().query(uri2, reminder_projection, selection2, selectionargs2, null)) { if (null != remindercursor) { if (remindercursor.movetofirst()) { list<calendarevent.eventreminders> reminders = new arraylist<>(); do { calendarevent.eventreminders reminders1 = new calendarevent.eventreminders(); reminders.add(reminders1); reminders1.setreminderid(remindercursor.getlong( remindercursor.getcolumnindex(calendarcontract.reminders._id))); reminders1.setremindereventid(remindercursor.getlong( remindercursor.getcolumnindex(calendarcontract.reminders.event_id))); reminders1.setreminderminute(remindercursor.getint( remindercursor.getcolumnindex(calendarcontract.reminders.minutes))); reminders1.setremindermethod(remindercursor.getint( remindercursor.getcolumnindex(calendarcontract.reminders.method))); } while (remindercursor.movetonext()); calendarevent.setreminders(reminders); } } } } while (cursor.movetonext()); cursor.close(); } return result; } /** * 判断日历账户中是否已经存在此事件 * * @param begin 事件开始时间 * @param end 事件结束时间 * @param title 事件标题 */ public static boolean iseventalreadyexist(context context, long begin, long end, string title) { string[] projection = new string[]{ calendarcontract.instances.begin, calendarcontract.instances.end, calendarcontract.instances.title }; cursor cursor = calendarcontract.instances.query( context.getcontentresolver(), projection, begin, end, title); return null != cursor && cursor.movetofirst() && cursor.getstring( cursor.getcolumnindex(calendarcontract.instances.title)).equals(title); } // ------------------------------- 日历事件相关 ----------------------------------- /** * 组装日历事件 */ private static void setupevent(calendarevent calendarevent, contentvalues event) { // 事件开始时间 event.put(calendarcontract.events.dtstart, calendarevent.getstart()); // 事件结束时间 event.put(calendarcontract.events.dtend, calendarevent.getend()); // 事件标题 event.put(calendarcontract.events.title, calendarevent.gettitle()); // 事件描述(对应手机系统日历备注栏) event.put(calendarcontract.events.description, calendarevent.getdescription()); // 事件地点 event.put(calendarcontract.events.event_location, calendarevent.geteventlocation()); // 事件时区 event.put(calendarcontract.events.event_timezone, timezone.getdefault().getid()); // 定义事件的显示,默认即可 event.put(calendarcontract.events.access_level, calendarcontract.events.access_default); // 事件的状态 event.put(calendarcontract.events.status, 0); // 设置事件提醒警报可用 event.put(calendarcontract.events.has_alarm, 1); // 设置事件忙 event.put(calendarcontract.events.availability, calendarcontract.events.availability_busy); if (null != calendarevent.getrrule()) { // 设置事件重复规则 event.put(calendarcontract.events.rrule, getfullrruleforrrule(calendarevent.getrrule(), calendarevent.getstart(), calendarevent.getend())); } } /** * 获取完整的重复规则(包含终止时间) * * @param rrule 重复规则 * @param begintime 开始时间 * @param endtime 结束时间 */ private static string getfullrruleforrrule(string rrule, long begintime, long endtime) { builder.delete(0, builder.length()); switch (rrule) { case rruleconstant.repeat_weekly_by_mo: case rruleconstant.repeat_weekly_by_tu: case rruleconstant.repeat_weekly_by_we: case rruleconstant.repeat_weekly_by_th: case rruleconstant.repeat_weekly_by_fr: case rruleconstant.repeat_weekly_by_sa: case rruleconstant.repeat_weekly_by_su: return builder.append(rrule).append(util.getfinalrrulemode(endtime)).tostring(); case rruleconstant.repeat_cycle_weekly: return builder.append(rrule).append(util.getweekfordate(begintime)).append("; until = ") .append(util.getfinalrrulemode(endtime)).tostring(); case rruleconstant.repeat_cycle_monthly: return builder.append(rrule).append(util.getdayofmonth(begintime)) .append("; until = ").append(util.getfinalrrulemode(endtime)).tostring(); default: return rrule; } } // ------------------------------- 通过intent启动系统日历 ----------------------------------- /* 日历的intent对象: 动作 描述 附加功能 action_view 打开指定时间的日历 无 action_view 查看由event_id指定的事件 开始时间,结束时间 action_edit 编辑由event_id指定的事件 开始时间,结束时间 action_insert 创建一个事件 所有 intent对象的附加功能: events.title 事件标题 calendarcontract.extra_event_begin_time 开始时间 calendarcontract.extra_event_end_time 结束时间 calendarcontract.extra_event_all_day 是否全天 events.event_location 事件地点 events.description 事件描述 intent.extra_emall 受邀者电子邮件,用逗号分隔 events.rrule 事件重复规则 events.access_level 事件私有还是公有 events.availability 预定事件是在忙时计数还是闲时计数 */ /** * 通过intent启动系统日历新建事件界面插入新的事件 * <p> * tip: 这将不再需要声明读写日历数据的权限 * * @param begintime 事件开始时间 * @param endtime 事件结束时间 * @param title 事件标题 * @param des 事件描述 * @param location 事件地点 * @param isallday 事件是否全天 */ public static void startcalendarforintenttoinsert(context context, long begintime, long endtime, string title, string des, string location, boolean isallday) { checkcalendaraccount(context); // fixme: 2019/3/6 vivo手机无法打开界面,找不到对应的activity com.bbk.calendar intent intent = new intent(intent.action_insert) .setdata(calendarcontract.events.content_uri) .putextra(calendarcontract.extra_event_begin_time, begintime) .putextra(calendarcontract.extra_event_end_time, endtime) .putextra(calendarcontract.events.all_day, isallday) .putextra(calendarcontract.events.title, title) .putextra(calendarcontract.events.description, des) .putextra(calendarcontract.events.event_location, location); if (null != intent.resolveactivity(context.getpackagemanager())) { context.startactivity(intent); } } /** * 通过intent启动系统日历来编辑指定id的事件 * <p> * * @param eventid 要编辑的事件id */ public static void startcalendarforintenttoedit(context context, long eventid) { checkcalendaraccount(context); uri uri = contenturis.withappendedid(calendarcontract.events.content_uri, eventid); intent intent = new intent(intent.action_edit).setdata(uri); if (null != intent.resolveactivity(context.getpackagemanager())) { context.startactivity(intent); } } /** * 通过intent启动系统日历来查看指定id的事件 * * @param eventid 要查看的事件id */ public static void startcalendarforintenttoview(context context, long eventid) { checkcalendaraccount(context); uri uri = contenturis.withappendedid(calendarcontract.events.content_uri, eventid); intent intent = new intent(intent.action_view).setdata(uri); if (null != intent.resolveactivity(context.getpackagemanager())) { context.startactivity(intent); } } // ----------------------------- 日历账户名相关设置 ----------------------------------- public static string getcalendarname() { return calendar_name; } public static void setcalendarname(string calendarname) { calendar_name = calendarname; } public static string getcalendaraccountname() { return calendar_account_name; } public static void setcalendaraccountname(string calendaraccountname) { calendar_account_name = calendaraccountname; } public static string getcalendardisplayname() { return calendar_display_name; } public static void setcalendardisplayname(string calendardisplayname) { calendar_display_name = calendardisplayname; } }
5、calendarevent类
public class calendarevent { // ----------------------- 事件属性 ----------------------- /** * 事件在表中的id */ private long id; /** * 事件所属日历账户的id */ private long calid; private string title; private string description; private string eventlocation; private int displaycolor; private int status; private long start; private long end; private string duration; private string eventtimezone; private string eventendtimezone; private int allday; private int accesslevel; private int availability; private int hasalarm; private string rrule; private string rdate; private int hasattendeedata; private int lastdate; private string organizer; private string isorganizer; // ---------------------------------------------------------------------------------------- /** * 注:此属性不属于calendarevent * 这里只是为了方便构造方法提供事件提醒时间 */ private int advancetime; // ---------------------------------------------------------------------------------------- // ----------------------- 事件提醒属性 ----------------------- private list<eventreminders> reminders; calendarevent() { } /** * 用于方便添加完整日历事件提供一个构造方法 * * @param title 事件标题 * @param description 事件描述 * @param eventlocation 事件地点 * @param start 事件开始时间 * @param end 事件结束时间 if is not a repeat event, this param is must need else null * @param advancetime 事件提醒时间{@link advancetime} * (if you don't need to remind the incoming parameters -2) * @param rrule 事件重复规则 {@link rruleconstant} {@code null} if dose not need */ public calendarevent(string title, string description, string eventlocation, long start, long end, int advancetime, string rrule) { this.title = title; this.description = description; this.eventlocation = eventlocation; this.start = start; this.end = end; this.advancetime = advancetime; this.rrule = rrule; } public int getadvancetime() { return advancetime; } public void setadvancetime(int advancetime) { this.advancetime = advancetime; } public long getid() { return id; } void setid(long id) { this.id = id; } public long getcalid() { return calid; } void setcalid(long calid) { this.calid = calid; } public string gettitle() { return title; } void settitle(string title) { this.title = title; } public string getdescription() { return description; } void setdescription(string description) { this.description = description; } public string geteventlocation() { return eventlocation; } void seteventlocation(string eventlocation) { this.eventlocation = eventlocation; } public int getdisplaycolor() { return displaycolor; } void setdisplaycolor(int displaycolor) { this.displaycolor = displaycolor; } public int getstatus() { return status; } void setstatus(int status) { this.status = status; } public long getstart() { return start; } void setstart(long start) { this.start = start; } public long getend() { return end; } void setend(long end) { this.end = end; } public string getduration() { return duration; } void setduration(string duration) { this.duration = duration; } public string geteventtimezone() { return eventtimezone; } void seteventtimezone(string eventtimezone) { this.eventtimezone = eventtimezone; } public string geteventendtimezone() { return eventendtimezone; } void seteventendtimezone(string eventendtimezone) { this.eventendtimezone = eventendtimezone; } public int getallday() { return allday; } void setallday(int allday) { this.allday = allday; } public int getaccesslevel() { return accesslevel; } void setaccesslevel(int accesslevel) { this.accesslevel = accesslevel; } public int getavailability() { return availability; } void setavailability(int availability) { this.availability = availability; } public int gethasalarm() { return hasalarm; } void sethasalarm(int hasalarm) { this.hasalarm = hasalarm; } public string getrrule() { return rrule; } void setrrule(string rrule) { this.rrule = rrule; } public string getrdate() { return rdate; } void setrdate(string rdate) { this.rdate = rdate; } public int gethasattendeedata() { return hasattendeedata; } void sethasattendeedata(int hasattendeedata) { this.hasattendeedata = hasattendeedata; } public int getlastdate() { return lastdate; } void setlastdate(int lastdate) { this.lastdate = lastdate; } public string getorganizer() { return organizer; } void setorganizer(string organizer) { this.organizer = organizer; } public string getisorganizer() { return isorganizer; } void setisorganizer(string isorganizer) { this.isorganizer = isorganizer; } public list<eventreminders> getreminders() { return reminders; } void setreminders(list<eventreminders> reminders) { this.reminders = reminders; } @nonnull @override public string tostring() { return "calendarevent{" + "\n id=" + id + "\n calid=" + calid + "\n title='" + title + '\'' + "\n description='" + description + '\'' + "\n eventlocation='" + eventlocation + '\'' + "\n displaycolor=" + displaycolor + "\n status=" + status + "\n start=" + start + "\n end=" + end + "\n duration='" + duration + '\'' + "\n eventtimezone='" + eventtimezone + '\'' + "\n eventendtimezone='" + eventendtimezone + '\'' + "\n allday=" + allday + "\n accesslevel=" + accesslevel + "\n availability=" + availability + "\n hasalarm=" + hasalarm + "\n rrule='" + rrule + '\'' + "\n rdate='" + rdate + '\'' + "\n hasattendeedata=" + hasattendeedata + "\n lastdate=" + lastdate + "\n organizer='" + organizer + '\'' + "\n isorganizer='" + isorganizer + '\'' + "\n reminders=" + reminders + '}'; } @override public int hashcode() { return (int) (id * 37 + calid); } /** * 事件提醒 */ static class eventreminders { // ----------------------- 事件提醒属性 ----------------------- private long reminderid; private long remindereventid; private int reminderminute; private int remindermethod; public long getreminderid() { return reminderid; } void setreminderid(long reminderid) { this.reminderid = reminderid; } public long getremindereventid() { return remindereventid; } void setremindereventid(long remindereventid) { this.remindereventid = remindereventid; } public int getreminderminute() { return reminderminute; } void setreminderminute(int reminderminute) { this.reminderminute = reminderminute; } public int getremindermethod() { return remindermethod; } void setremindermethod(int remindermethod) { this.remindermethod = remindermethod; } } }
6、util类
public class util { /** * 获取日历事件结束日期 * * @param time time in ms */ private static string getenddate(long time) { date date = new date(time); simpledateformat format = new simpledateformat("yyyymmdd", locale.getdefault()); return format.format(date); } /** * 获取最终日历事件重复规则 * * @param time time in ms * "t235959" {@linkplain com.kyle.calendarprovider.calendar.rruleconstant #51} */ public static string getfinalrrulemode(long time) { return getenddate(time) + "t235959z"; } /** * 格式化星期 */ private static string formatweek(int week) { switch (week) { case 0: return "su"; case 1: return "mo"; case 2: return "tu"; case 3: return "we"; case 4: return "th"; case 5: return "fr"; case 6: return "sa"; default: return null; } } /** * 获取重复周 * * @param time time in ms */ public static string getweekfordate(long time) { date date = new date(time); calendar calendar = calendar.getinstance(); calendar.settime(date); int week = calendar.get(calendar.day_of_week) - 1; if (week < 0) { week = 0; } return formatweek(week); } /** * 获取指定时间段在一个月中的哪一天 * * @param time time in ms */ public static int getdayofmonth(long time) { date date = new date(time); calendar calendar = calendar.getinstance(); calendar.settime(date); return calendar.get(calendar.day_of_month); } /** * check null */ public static void checkcontextnull(context context) { if (null == context) { throw new illegalargumentexception("context can not be null"); } } }
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。