4

Possible Duplicate:
How to add calendar events in Android?

how can we add reminder data in android calendar?

Community
  • 1
  • 1
Kandha
  • 3,659
  • 12
  • 35
  • 50

4 Answers4

17

Here is a class I used for ICS

import android.app.Activity;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.CalendarContract;
import android.provider.CalendarContract.Calendars;
import android.provider.CalendarContract.Events;
import android.provider.CalendarContract.Reminders;
import android.util.Log;

public class IcsCalendarHelper {

//Remember to initialize this activityObj first, by calling initActivityObj(this) from 
//your activity  
private static final String DEBUG_TAG = "CalendarActivity";
private static Activity activityObj;

public static void initActivityObj(Activity obj)
{
        activityObj = obj;
}

public static void IcsMakeNewCalendarEntry(String title,String description,String location,long startTime,long endTime, int allDay,int hasAlarm, int calendarId,int selectedReminderValue) {

        ContentResolver cr = activityObj.getContentResolver();
        ContentValues values = new ContentValues();
        values.put(Events.DTSTART, startTime);
        values.put(Events.DTEND, endTime);
        values.put(Events.TITLE, title);
        values.put(Events.DESCRIPTION, description);
        values.put(Events.CALENDAR_ID, calendarId);

        if (allDay == 1)
        {
            values.put(Events.ALL_DAY, true);
        }

        if (hasAlarm==1)
        {
            values.put(Events.HAS_ALARM, true);
        }

        //Get current timezone
        values.put(Events.EVENT_TIMEZONE,TimeZone.getDefault().getID());
        Log.i(DEBUG_TAG, "Timezone retrieved=>"+TimeZone.getDefault().getID());
        Uri uri = cr.insert(Events.CONTENT_URI, values);
        Log.i(DEBUG_TAG, "Uri returned=>"+uri.toString());
        // get the event ID that is the last element in the Uri
        long eventID = Long.parseLong(uri.getLastPathSegment());

        if (hasAlarm==1)
        {
            ContentValues reminders = new ContentValues();
            reminders.put(Reminders.EVENT_ID, eventID);
            reminders.put(Reminders.METHOD, Reminders.METHOD_ALERT);
            reminders.put(Reminders.MINUTES, selectedReminderValue);

            Uri uri2 = cr.insert(Reminders.CONTENT_URI, reminders);
        }


}

}

If your app is targeting Android 6.0 and above, the class below contains helper functions to request for READ/WRITE calendar permissions during runtime.

A working example in GitHub

package testpreference.com.testcalendar;

import android.Manifest;
import android.app.Activity;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.net.Uri;
import android.provider.CalendarContract.Events;
import android.provider.CalendarContract.Reminders;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.util.Log;

import java.util.ArrayList;
import java.util.Hashtable;
import java.util.List;
import java.util.TimeZone;

public class CalendarHelper {

    //Remember to initialize this activityObj first, by calling initActivityObj(this) from
//your activity
    private static final String TAG = "CalendarHelper";
    public static final int CALENDARHELPER_PERMISSION_REQUEST_CODE = 99;


    public static void MakeNewCalendarEntry(Activity caller,String title,String description,String location,long startTime,long endTime, boolean allDay,boolean hasAlarm, int calendarId,int selectedReminderValue) {

        ContentResolver cr = caller.getContentResolver();
        ContentValues values = new ContentValues();
        values.put(Events.DTSTART, startTime);
        values.put(Events.DTEND, endTime);
        values.put(Events.TITLE, title);
        values.put(Events.DESCRIPTION, description);
        values.put(Events.CALENDAR_ID, calendarId);
        values.put(Events.STATUS, Events.STATUS_CONFIRMED);


        if (allDay)
        {
            values.put(Events.ALL_DAY, true);
        }

        if (hasAlarm)
        {
            values.put(Events.HAS_ALARM, true);
        }

        //Get current timezone
        values.put(Events.EVENT_TIMEZONE, TimeZone.getDefault().getID());
        Log.i(TAG, "Timezone retrieved=>"+TimeZone.getDefault().getID());
        Uri uri = cr.insert(Events.CONTENT_URI, values);
        Log.i(TAG, "Uri returned=>"+uri.toString());
        // get the event ID that is the last element in the Uri
        long eventID = Long.parseLong(uri.getLastPathSegment());

        if (hasAlarm)
        {
            ContentValues reminders = new ContentValues();
            reminders.put(Reminders.EVENT_ID, eventID);
            reminders.put(Reminders.METHOD, Reminders.METHOD_ALERT);
            reminders.put(Reminders.MINUTES, selectedReminderValue);

            Uri uri2 = cr.insert(Reminders.CONTENT_URI, reminders);
        }


    }

    public static void requestCalendarReadWritePermission(Activity caller)
    {
        List<String> permissionList = new ArrayList<String>();

        if  (ContextCompat.checkSelfPermission(caller,Manifest.permission.WRITE_CALENDAR)!=PackageManager.PERMISSION_GRANTED)
        {
            permissionList.add(Manifest.permission.WRITE_CALENDAR);

        }

        if  (ContextCompat.checkSelfPermission(caller,Manifest.permission.READ_CALENDAR)!=PackageManager.PERMISSION_GRANTED)
        {
            permissionList.add(Manifest.permission.READ_CALENDAR);

        }

        if (permissionList.size()>0)
        {
            String [] permissionArray = new String[permissionList.size()];

            for (int i=0;i<permissionList.size();i++)
            {
                permissionArray[i] = permissionList.get(i);
            }

            ActivityCompat.requestPermissions(caller,
                    permissionArray,
                    CALENDARHELPER_PERMISSION_REQUEST_CODE);
        }

    }

    public static Hashtable listCalendarId(Context c) {

        if (haveCalendarReadWritePermissions((Activity)c)) {

            String projection[] = {"_id", "calendar_displayName"};
            Uri calendars;
            calendars = Uri.parse("content://com.android.calendar/calendars");

            ContentResolver contentResolver = c.getContentResolver();
            Cursor managedCursor = contentResolver.query(calendars, projection, null, null, null);

            if (managedCursor.moveToFirst())
            {
                String calName;
                String calID;
                int cont = 0;
                int nameCol = managedCursor.getColumnIndex(projection[1]);
                int idCol = managedCursor.getColumnIndex(projection[0]);
                Hashtable<String,String> calendarIdTable = new Hashtable<>();

                do
                {
                    calName = managedCursor.getString(nameCol);
                    calID = managedCursor.getString(idCol);
                    Log.v(TAG, "CalendarName:" + calName + " ,id:" + calID);
                    calendarIdTable.put(calName,calID);
                    cont++;
                } while (managedCursor.moveToNext());
                managedCursor.close();

                return calendarIdTable;
            }

        }

        return null;

    }

    public static boolean haveCalendarReadWritePermissions(Activity caller)
    {
        int permissionCheck = ContextCompat.checkSelfPermission(caller,
                Manifest.permission.READ_CALENDAR);

        if (permissionCheck== PackageManager.PERMISSION_GRANTED)
        {
            permissionCheck = ContextCompat.checkSelfPermission(caller,
                    Manifest.permission.WRITE_CALENDAR);

            if (permissionCheck== PackageManager.PERMISSION_GRANTED)
            {
                return true;
            }
        }

        return false;
    }

}
ChinLoong
  • 1,735
  • 24
  • 26
  • thanks, it worked for me on android 4.4, does this mean that it'll work for all android versions after 4.0? – Hamzeh Soboh Mar 22 '15 at 12:33
  • Its not working 6.0.... Event add successfully but reminder not added. please help me – Anuj Zunjarrao Dec 17 '15 at 11:38
  • 1
    I have directly created a calendar event through my app and added reminder also. They are working perfectly. But when I click reminder notification, it's opening device calendar event. Now I want to customize reminder notification to load my app without loading default calendar. Can I achieve this ? – Nooruddin Lakhani Apr 27 '16 at 08:22
  • Maybe you can use AlarmManager to fire up a notification of your own. See http://stackoverflow.com/questions/14002692/alarmmanager-at-specific-date-and-time – ChinLoong Apr 27 '16 at 09:13
  • @NooruddinLakhani were you able to get the custom notification working? – Tejas Sherdiwala Jun 24 '17 at 18:36
5

Hi use the following code to add the event programmatically to the calendar.

        Uri EVENTS_URI = Uri.parse(getCalendarUriBase(this) + "events");
        ContentResolver cr = getContentResolver();
        ContentValues values = new ContentValues();
        values.put("calendar_id", id);
        values.put("title", tasktitle);
        values.put("allDay", 0);
        values.put("dtstart", settime); 
        values.put("dtend", cal.getTimeInMillis()+60*60*1000); 
        values.put("description", description);
        values.put("visibility", 0);
        values.put("transparency", 0);
        values.put("hasAttendeeData", 1);
        values.put("hasAlarm", 0);
        event = cr.insert(EVENT_URI, values);
        event1=event; 
        dat1 = event.toString();
        long id=-1;
        if (event != null)
        {
             id = Long.parseLong(event.getLastPathSegment());
             ContentValues values1 = new ContentValues();
             values1.put("event_id", id);
             values1.put("method", 1); //METHOD_ALERT

            Uri reminder = Uri.parse(getCalendarUriBase(this) + "reminders");
            this.getContentResolver().insert(reminder, values1);


                 ContentValues attendees = new ContentValues();
                 attendees.put("event_id", id);
                 attendees.put("attendeeEmail", partmail1);
                 attendees.put("attendeeRelationship", 2);//RELATIONSHIP_ATTENDEE
                 attendees.put("attendeeStatus", 3); //ATTENDEE_STATUS_INVITED       
                 attendees.put("attendeeType", 1); //TYPE_REQUIRED

                id1=(int)id;
                alarmid = (int) id;
                Uri attendeesUri = null;
                if (Integer.parseInt(Build.VERSION.SDK) >= 8 )
                {
                         attendeesUri = Uri.parse("content://com.android.calendar/attendees");
                }
                else if(Integer.parseInt(Build.VERSION.SDK) < 8)
                {
                        attendeesUri = Uri.parse("content://calendar/attendees");
                }
                this.getContentResolver().insert(attendeesUri, attendees);

                Toast.makeText(this, "Task Scheduled Successfully", Toast.LENGTH_SHORT).show();
            }



        // reminder insert
        Uri REMINDERS_URI = Uri.parse(getCalendarUriBase(this) + "reminders");
        values = new ContentValues();
        values.put( "event_id", id);
        values.put( "method", 1 );
        values.put( "minutes", 0 );
        cr.insert( REMINDERS_URI, values );
Pattabi Raman
  • 5,814
  • 10
  • 39
  • 60
3

Check How to add calendar events in Android? with the solution by oriharel. It's in fact very good because it asks the user in which calendar to put the event.

Community
  • 1
  • 1
Sebastian Roth
  • 11,344
  • 14
  • 61
  • 110
2

Use the Google Calendar GData API to modify the user's calendar.

CommonsWare
  • 986,068
  • 189
  • 2,389
  • 2,491