oikonomopo oikonomopo - 3 months ago 36
Java Question

How to add calendar events to default calendar, silently without Intent, in android 4?

I want to add calendar events programmatically (directly) in android 4+. Is it this possible to be tested on emulator? I don't own an android phone. Some sample code would be appreciated. I read Calendar Provider of android developers but I'm confused. How can I add events to the default calendar of a user? I don't need to be synced.

EDIT: I do not want to launch an event adding Intent. Instead I want to add them completely from code and not launch another activity. I need to be able to test on an emulator that the events will be added to the main calendar of the default user of the device. How do I set up an emulator to view the default calendar of the user?


Here is a working example of what i eventually made it:

 ContentResolver cr = ctx.getContentResolver();
        ContentValues values = new ContentValues();

        values.put(CalendarContract.Events.DTSTART, dtstart);
        values.put(CalendarContract.Events.TITLE, title);
        values.put(CalendarContract.Events.DESCRIPTION, comment);

        TimeZone timeZone = TimeZone.getDefault();
        values.put(CalendarContract.Events.EVENT_TIMEZONE, timeZone.getID());

        // default calendar
        values.put(CalendarContract.Events.CALENDAR_ID, 1);

        values.put(CalendarContract.Events.RRULE, "FREQ=DAILY;UNTIL="
                + dtUntill);
        //for one hour
        values.put(CalendarContract.Events.DURATION, "+P1H");

        values.put(CalendarContract.Events.HAS_ALARM, 1);

        // insert event to calendar
        Uri uri = cr.insert(CalendarContract.Events.CONTENT_URI, values);

where dtuntil is

    SimpleDateFormat yyyyMMdd = new SimpleDateFormat("yyyyMMdd");
    Calendar dt = Calendar.getInstance();

    //where untilDate is a date instance of your choice,for example 30/01/2012

    //if you want the event until 30/01/2012 we add one day from our day because UNTIL in RRule sets events Before the last day want for event
    dt.add(Calendar.DATE, 1);
    String dtUntill = yyyyMMdd.format(dt.getTime());

See also Recurrence Rule