以编程方式在Android日历中添加提醒?

时间:2010-09-04 11:55:24

标签: android

  

可能重复:
  How to add calendar events in Android?

我们如何在Android日历中添加提醒数据?

4 个答案:

答案 0 :(得分:15)

这是我用于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);
        }


}

}

如果您的应用是针对Android 6.0及更高版本,则下面的类包含帮助函数,以在运行时请求READ / WRITE日历权限。

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;
    }

}

答案 1 :(得分:4)

您可以使用以下代码以编程方式将事件添加到日历中。

        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 );

答案 2 :(得分:3)

使用解决方案 oriharel 检查How to add calendar events in Android?。事实上它非常好,因为它要求用户在哪个日历中放置事件。

答案 3 :(得分:2)

使用Google Calendar GData API修改用户的日历。