我想在Android 2.2设备上获取日历事件更新(当添加新事件或删除现有事件时)? 我是初学者,请告诉我一步一步的解决方案..
答案 0 :(得分:2)
此代码可能对您有所帮助:)
public class myCalendar
{
static Cursor cursor;
public static void readCalendar(Context context) {
ContentResolver contentResolver = context.getContentResolver();
// Fetch a list of all calendars synced with the device, their display names and whether the
// user has them selected for display.
cursor = contentResolver.query(Uri.parse("content://com.android.calendar/calendars"),
(new String[] { "_id", "displayName", "selected"}), null, null, null);
HashSet<String> calendarIds = new HashSet<String>();
try
{
System.out.println("Count="+cursor.getCount());
if(cursor.getCount() > 0)
{
System.out.println("the control is just inside of the cursor.count loop");
while (cursor.moveToNext()) {
String _id = cursor.getString(0);
String displayName = cursor.getString(1);
Boolean selected = !cursor.getString(2).equals("0");
System.out.println("Id: " + _id + " Display Name: " + displayName + " Selected: " + selected);
calendarIds.add(_id);
}
}
}
catch(AssertionError ex)
{
ex.printStackTrace();
}
catch(Exception e)
{
e.printStackTrace();
}
// For each calendar, display all the events from the previous week to the end of next week.
for (String id : calendarIds) {
Uri.Builder builder = Uri.parse("content://com.android.calendar/instances/when").buildUpon();
//Uri.Builder builder = Uri.parse("content://com.android.calendar/calendars").buildUpon();
long now = new Date().getTime();
ContentUris.appendId(builder, now - DateUtils.DAY_IN_MILLIS * 10000);
ContentUris.appendId(builder, now + DateUtils.DAY_IN_MILLIS * 10000);
Cursor eventCursor = contentResolver.query(builder.build(),
new String[] { "title", "begin", "end", "allDay"}, "Calendars._id=" + 1,
null, "startDay ASC, startMinute ASC");
System.out.println("eventCursor count="+eventCursor.getCount());
if(eventCursor.getCount()>0)
{
eventCursor.moveToFirst();
while (eventCursor.moveToNext())
{
Object beg_date,beg_time,end_date,end_time;
final String title = eventCursor.getString(0);
final Date begin = new Date(eventCursor.getLong(1));
final Date end = new Date(eventCursor.getLong(2));
final Boolean allDay = !eventCursor.getString(3).equals("0");
/* System.out.println("Title: " + title + " Begin: " + begin + " End: " + end +
" All Day: " + allDay);
*/
System.out.println("Title:"+title);
System.out.println("Begin:"+begin);
System.out.println("End:"+end);
System.out.println("All Day:"+allDay);
System.out.println("only date begin of events="+begin.getDate());
System.out.println("only begin time of events="+begin.getHours() + ":" +begin.getMinutes() + ":" +begin.getSeconds());
System.out.println("only date begin of events="+end.getDate());
System.out.println("only begin time of events="+end.getHours() + ":" +end.getMinutes() + ":" +end.getSeconds());
beg_date = begin.getDate();
beg_time = begin.getHours()+":"+begin.getMinutes();
end_date = end.getDate();
end_time = end.getHours()+":"+end.getMinutes();
}
}
break;
}
}
}