add calendar event without opening calendar

2019-04-14 03:49发布

问题:

In my app, the user can set up to 3 reminders for a task, but every time I press the "set reminder" button it opens up the calendar app. Is there any way to set the calendar events without opening the default calendar app? I just want to add an event without starting the calendar activity.

This is what my code looks like now:

Calendar beginTime = Calendar.getInstance();
beginTime.set(2013, Calendar.MAY, 10, 3, 00);
startMillis = beginTime.getTimeInMillis();
Calendar endTime = Calendar.getInstance();
endTime.set(2012, Calendar.MAY, 10, 4, 00);
endMillis = endTime.getTimeInMillis();

Intent intent = new Intent(Intent.ACTION_INSERT);
intent.setType("vnd.android.cursor.item/event");
intent.putExtra(Events.TITLE, "Test Android");
intent.putExtra(Events.EVENT_LOCATION, "Test Location");
intent.putExtra(Events.DESCRIPTION, "Test Description Examples");

intent.putExtra(Events.DTSTART, startMillis);
intent.putExtra(Events.DTEND, endMillis);
intent.putExtra(Events.ALL_DAY, false);
intent.putExtra(Events.EVENT_END_TIMEZONE, "Europe/London");


intent.putExtra(Events.ACCESS_LEVEL, Events.ACCESS_PRIVATE);
intent.putExtra(Events.AVAILABILITY, Events.AVAILABILITY_BUSY);

回答1:

This will look something like this:

    final ContentValues event = new ContentValues();
    event.put(Events.CALENDAR_ID, 1);

    event.put(Events.TITLE, title);
    event.put(Events.DESCRIPTION, description);
    event.put(Events.EVENT_LOCATION, location);

    event.put(Events.DTSTART, startTimeMillis);
    event.put(Events.DTEND, endTimeMillis);
    event.put(Events.ALL_DAY, 0);   // 0 for false, 1 for true
    event.put(Events.HAS_ALARM, 1); // 0 for false, 1 for true

    String timeZone = TimeZone.getDefault().getID();
    event.put(Events.EVENT_TIMEZONE, timeZone);

    Uri baseUri;
    if (Build.VERSION.SDK_INT >= 8) {
        baseUri = Uri.parse("content://com.android.calendar/events");
    } else {
        baseUri = Uri.parse("content://calendar/events");
    }

    context.getContentResolver().insert(baseUri, event);