结果表明,默认日历ID可能因设备而异。
私有int getCalendarId(){
Cursor cursor = null;
ContentResolver contentResolver = getCurrentActiveContext().getContentResolver();
Uri calendars = CalendarContract.Calendars.CONTENT_URI;
String[] EVENT_PROJECTION = new String[]{
CalendarContract.Calendars._ID, // 0
CalendarContract.Calendars.ACCOUNT_NAME, // 1
CalendarContract.Calendars.CALENDAR_DISPLAY_NAME, // 2
CalendarContract.Calendars.OWNER_ACCOUNT, // 3
CalendarContract.Calendars.IS_PRIMARY // 4
};
int PROJECTION_ID_INDEX = 0;
int PROJECTION_ACCOUNT_NAME_INDEX = 1;
int PROJECTION_DISPLAY_NAME_INDEX = 2;
int PROJECTION_OWNER_ACCOUNT_INDEX = 3;
int PROJECTION_VISIBLE = 4;
cursor = contentResolver.query(calendars, EVENT_PROJECTION, null, null, null);
if (cursor.moveToFirst()) {
String calName;
long calId = 0;
String visible;
do {
calName = cursor.getString(PROJECTION_DISPLAY_NAME_INDEX);
calId = cursor.getLong(PROJECTION_ID_INDEX);
visible = cursor.getString(PROJECTION_VISIBLE);
Log.e("Calendar Id : ", "" + calId + " : " + calName + " : " + visible);
if (visible.equals("1")) {
return (int) calId;
}
} while (cursor.moveToNext());
return (int) calId;
}
return 1;
}
下面的代码只是为了了解有多少日历及其id的信息
String projection[] = {"_id", "calendar_displayName"};
Uri calendars;
calendars = Uri.parse("content://com.android.calendar/calendars");
ContentResolver contentResolver = getCurrentContext().getContentResolver();
Cursor managedCursor = contentResolver.query(calendars, projection, null, null, null);
String calID="1";
if (managedCursor.moveToFirst()){
String calName;
int cont= 0;
int nameCol = managedCursor.getColumnIndex(projection[1]);
int idCol = managedCursor.getColumnIndex(projection[0]);
do {
calName = managedCursor.getString(nameCol);
calID = managedCursor.getString(idCol);
Log.e("calName",""+calName);
Log.e("calID",""+calID);
cont++;
} while(managedCursor.moveToNext());
managedCursor.close();
}