某些Android手机上的活动未添加到日历

时间:2015-08-17 04:02:34

标签: android android-calendar

我使用下面的代码将事件添加到android上的日历

public void addEvent(String datetime) { 
        String eventdate;
        {
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy/MM/dd HH:mm");
        final Calendar cal = Calendar.getInstance();
        try {

            cal.setTime(formatter.parse(datetime));
            eventdate = cal.get(Calendar.YEAR)+"/"+cal.get(Calendar.MONTH)+"/"+cal.get(Calendar.DAY_OF_MONTH)+" "+cal.get(Calendar.HOUR_OF_DAY)+":"+cal.get(Calendar.MINUTE);
            //Log.e("Event date ", eventdate);
        } catch (Exception e) {
            Log.e("Catch ", "",e);
        }
        ContentValues event = new ContentValues();
        event.put("calendar_id", 3);
        event.put("_id", eventid);
        event.put("title", mytitle);
        event.put("description", mydescription);
        event.put("eventTimezone", TimeZone.getDefault().getID());
        event.put("dtstart", cal.getTimeInMillis());
        event.put("dtend", cal.getTimeInMillis()+60*60*1000);
        event.put("hasAlarm", 1); // 0 for false, 1 for true

        String eventUriString = "content://com.android.calendar/events";

        Uri eventUri = getApplicationContext()
        .getContentResolver()
        .insert(Uri.parse(eventUriString), event);

        System.out.println("event"+eventUri);
    }

以下代码将事件添加到运行android lollipop的HTC手机中,但它在Micromax和运行android Jellybean的三星等手机上返回null。这种行为的原因是什么?我是否需要从设置中打开任何内容?

1 个答案:

答案 0 :(得分:1)

尝试使用Events类提供的常量。

ContentResolver cr = yourContext.getContentResolver();
ContentValues event = new ContentValues();
event.put(Events.DTSTART,  cal.getTimeInMillis());
event.put(Events.DTEND, cal.getTimeInMillis() + 60 * 60 * 1000);
event.put(Events.TITLE, mytitle);
event.put(Events.DESCRIPTION, mydescription);
event.put(Events.CALENDAR_ID, calID);
event.put(Events.EVENT_TIMEZONE, TimeZone.getDefault().getID());
...
Uri uri = cr.insert(Events.CONTENT_URI, event);

此插入事件的事件ID可以从此方法获取

long eventID = Long.parseLong(uri.getLastPathSegment());

检查日历提供商中的标题添加活动 http://developer.android.com/guide/topics/providers/calendar-provider.html

如果你想在活动中插入_id,你应该检查它是否已经存在

Uri event = ContentUris.withAppendedId(Events.CONTENT_URI, _id);
Cursor cursor = managedQuery(event, null, null, null);
if (cursor.getCount() == 1) {
  //the event exists.. so may be you want to update it
} else {
  // you can insert your id
}