首页 > 代码库 > 获取与修改android自带日历日程

获取与修改android自带日历日程

Android中的日历,只有真机才有,模拟上是没有的,所以测试环境一定要真机!!

因为日历是系统自带的,所以我们读写它一定要申请权限,也就是在AndroidManifest.xml加如下两行代码(一个读一个写):

<!-- get calendar read and write permission -->
    <uses-permission android:name="android.permission.READ_CALENDAR" />
    <uses-permission android:name="android.permission.WRITE_CALENDAR" />
日历日程URL在2.2以后版本有所改变

// 为了兼容不同版本的日历,2.2以后url发生改变
	private static String calanderEventURL = "";
	static {
		if (Integer.parseInt(Build.VERSION.SDK) >= 8) {
			calanderEventURL = "content://com.android.calendar/events";
		} else {
			calanderEventURL = "content://calendar/events";
		}

	}
下面是获取日程的主要代码:
ContentResolver cr = context.getContentResolver();
		// 日历里面相应的Event的URI
		Uri uri = Uri.parse(calanderEventURL);
		Cursor cursor = cr.query(uri, null, null, null, null);
		while (cursor.moveToNext()) {
			CalendarEvent cde = new CalendarEvent();
			cde.setCalendar_id(cursor.getString(cursor
					.getColumnIndex(Events.CALENDAR_ID)));
			cde.setTitle(cursor.getString(cursor.getColumnIndex(Events.TITLE)));
			cde.setDtstart(cursor.getString(cursor
					.getColumnIndex(Events.DTSTART)));
			cde.setDtend(cursor.getString(cursor.getColumnIndex(Events.DTEND)));
			cde.setDuration(cursor.getString(cursor
					.getColumnIndex(Events.DURATION)));
			cde.setRrule(cursor.getString(cursor.getColumnIndex(Events.RRULE)));
			cde.setEventTimezone(cursor.getString(cursor
					.getColumnIndex(Events.EVENT_TIMEZONE)));
			calendarEvents.add(cde);
		}
下面是写入日程的主要代码

写入的时候这几个字段是必须的所以我就只写了这几个字段了

ContentResolver cr = context.getContentResolver();
		// 日历里面相应的Event的URI
		Uri uri = Uri.parse(calanderEventURL);
		Cursor cursor = cr.query(uri, null, null, null, null);
		while (cursor.moveToNext()) {
			CalendarEvent cde = new CalendarEvent();
			cde.setCalendar_id(cursor.getString(cursor
					.getColumnIndex(Events.CALENDAR_ID)));
			cde.setTitle(cursor.getString(cursor.getColumnIndex(Events.TITLE)));
			cde.setDtstart(cursor.getString(cursor
					.getColumnIndex(Events.DTSTART)));
			cde.setDtend(cursor.getString(cursor.getColumnIndex(Events.DTEND)));
			cde.setDuration(cursor.getString(cursor
					.getColumnIndex(Events.DURATION)));
			cde.setRrule(cursor.getString(cursor.getColumnIndex(Events.RRULE)));
			cde.setEventTimezone(cursor.getString(cursor
					.getColumnIndex(Events.EVENT_TIMEZONE)));
			calendarEvents.add(cde);
		}



获取与修改android自带日历日程