如何在Android中添加日历事件?

问题描述 投票:0回答:13

我刚刚开始了解 Android,今天在一个项目会议上有人说 Android 没有本机日历应用程序,因此用户只需使用他们喜欢的任何日历应用程序即可。

这是真的吗?如果是,我如何以编程方式将事件添加到用户的日历中?它们有共同的 API 吗?

就其价值而言,我们的目标可能是 Android 2.x。

android calendar
13个回答
299
投票

在您的代码中尝试一下:

Calendar cal = Calendar.getInstance();              
Intent intent = new Intent(Intent.ACTION_EDIT);
intent.setType("vnd.android.cursor.item/event");
intent.putExtra("beginTime", cal.getTimeInMillis());
intent.putExtra("allDay", true);
intent.putExtra("rrule", "FREQ=YEARLY");
intent.putExtra("endTime", cal.getTimeInMillis()+60*60*1000);
intent.putExtra("title", "A Test Event from android app");
startActivity(intent);

66
投票

在您的代码中使用此API..它将帮助您插入事件,可以启用带有提醒的事件和带有会议的事件...此API适用于平台2.1及以上 那些使用小于 2.1 而不是 content://com.android.calendar/events 的人使用 content://calendar/events

 public static long pushAppointmentsToCalender(Activity curActivity, String title, String addInfo, String place, int status, long startDate, boolean needReminder, boolean needMailService) {
    /***************** Event: note(without alert) *******************/

    String eventUriString = "content://com.android.calendar/events";
    ContentValues eventValues = new ContentValues();

    eventValues.put("calendar_id", 1); // id, We need to choose from
                                        // our mobile for primary
                                        // its 1
    eventValues.put("title", title);
    eventValues.put("description", addInfo);
    eventValues.put("eventLocation", place);

    long endDate = startDate + 1000 * 60 * 60; // For next 1hr

    eventValues.put("dtstart", startDate);
    eventValues.put("dtend", endDate);

    // values.put("allDay", 1); //If it is bithday alarm or such
    // kind (which should remind me for whole day) 0 for false, 1
    // for true
    eventValues.put("eventStatus", status); // This information is
    // sufficient for most
    // entries tentative (0),
    // confirmed (1) or canceled
    // (2):
    eventValues.put("eventTimezone", "UTC/GMT +2:00");
   /*Comment below visibility and transparency  column to avoid java.lang.IllegalArgumentException column visibility is invalid error */

    /*eventValues.put("visibility", 3); // visibility to default (0),
                                        // confidential (1), private
                                        // (2), or public (3):
    eventValues.put("transparency", 0); // You can control whether
                                        // an event consumes time
                                        // opaque (0) or transparent
                                        // (1).
      */
    eventValues.put("hasAlarm", 1); // 0 for false, 1 for true

    Uri eventUri = curActivity.getApplicationContext().getContentResolver().insert(Uri.parse(eventUriString), eventValues);
    long eventID = Long.parseLong(eventUri.getLastPathSegment());

    if (needReminder) {
        /***************** Event: Reminder(with alert) Adding reminder to event *******************/

        String reminderUriString = "content://com.android.calendar/reminders";

        ContentValues reminderValues = new ContentValues();

        reminderValues.put("event_id", eventID);
        reminderValues.put("minutes", 5); // Default value of the
                                            // system. Minutes is a
                                            // integer
        reminderValues.put("method", 1); // Alert Methods: Default(0),
                                            // Alert(1), Email(2),
                                            // SMS(3)

        Uri reminderUri = curActivity.getApplicationContext().getContentResolver().insert(Uri.parse(reminderUriString), reminderValues);
    }

    /***************** Event: Meeting(without alert) Adding Attendies to the meeting *******************/

    if (needMailService) {
        String attendeuesesUriString = "content://com.android.calendar/attendees";

        /********
         * To add multiple attendees need to insert ContentValues multiple
         * times
         ***********/
        ContentValues attendeesValues = new ContentValues();

        attendeesValues.put("event_id", eventID);
        attendeesValues.put("attendeeName", "xxxxx"); // Attendees name
        attendeesValues.put("attendeeEmail", "[email protected]");// Attendee
                                                                            // E
                                                                            // mail
                                                                            // id
        attendeesValues.put("attendeeRelationship", 0); // Relationship_Attendee(1),
                                                        // Relationship_None(0),
                                                        // Organizer(2),
                                                        // Performer(3),
                                                        // Speaker(4)
        attendeesValues.put("attendeeType", 0); // None(0), Optional(1),
                                                // Required(2), Resource(3)
        attendeesValues.put("attendeeStatus", 0); // NOne(0), Accepted(1),
                                                    // Decline(2),
                                                    // Invited(3),
                                                    // Tentative(4)

        Uri attendeuesesUri = curActivity.getApplicationContext().getContentResolver().insert(Uri.parse(attendeuesesUriString), attendeesValues);
    }

    return eventID;

}

59
投票

我使用了下面的代码,它解决了我在 ICS 中的默认设备日历中添加事件以及在 ICS 版本较小的版本上添加事件的问题

    if (Build.VERSION.SDK_INT >= 14) {
        Intent intent = new Intent(Intent.ACTION_INSERT)
        .setData(Events.CONTENT_URI)
        .putExtra(CalendarContract.EXTRA_EVENT_BEGIN_TIME, beginTime.getTimeInMillis())
        .putExtra(CalendarContract.EXTRA_EVENT_END_TIME, endTime.getTimeInMillis())
        .putExtra(Events.TITLE, "Yoga")
        .putExtra(Events.DESCRIPTION, "Group class")
        .putExtra(Events.EVENT_LOCATION, "The gym")
        .putExtra(Events.AVAILABILITY, Events.AVAILABILITY_BUSY)
        .putExtra(Intent.EXTRA_EMAIL, "[email protected],[email protected]");
         startActivity(intent);
}

    else {
        Calendar cal = Calendar.getInstance();              
        Intent intent = new Intent(Intent.ACTION_EDIT);
        intent.setType("vnd.android.cursor.item/event");
        intent.putExtra("beginTime", cal.getTimeInMillis());
        intent.putExtra("allDay", true);
        intent.putExtra("rrule", "FREQ=YEARLY");
        intent.putExtra("endTime", cal.getTimeInMillis()+60*60*1000);
        intent.putExtra("title", "A Test Event from android app");
        startActivity(intent);
        }

希望对您有帮助......


41
投票

从 Android 版本 4.0 开始可以使用官方 API 和意图与可用的日历提供商进行交互。


16
投票

如何以编程方式将事件添加到用户的日历?

哪个日历?

他们有共享的通用 API 吗?

不,就像 Windows 日历应用程序有一个“他们都共享的通用 API”一样。有一些通用的数据格式(例如 iCalendar)和互联网协议(例如 CalDAV),但没有通用的 API。有些日历应用程序甚至不提供 API。

如果您希望集成特定的日历应用程序,请联系其开发人员并确定他们是否提供 API。例如,Mayra 引用的 Android 开源项目中的日历应用程序不提供任何记录和支持的 API。 Google 甚至明确告诉开发人员不要使用 Mayra 引用的教程中概述的技术。

另一个选项是您将事件添加到相关的互联网日历中。例如,从 Android 开源项目向日历应用程序添加事件的最佳方法是通过适当的 GData API 将事件添加到用户的 Google 日历。


更新

Android 4.0(API 级别 14)添加了

CalendarContract

 
ContentProvider


10
投票
试试这个,

Calendar beginTime = Calendar.getInstance(); beginTime.set(yearInt, monthInt - 1, dayInt, 7, 30); ContentValues l_event = new ContentValues(); l_event.put("calendar_id", CalIds[0]); l_event.put("title", "event"); l_event.put("description", "This is test event"); l_event.put("eventLocation", "School"); l_event.put("dtstart", beginTime.getTimeInMillis()); l_event.put("dtend", beginTime.getTimeInMillis()); l_event.put("allDay", 0); l_event.put("rrule", "FREQ=YEARLY"); // status: 0~ tentative; 1~ confirmed; 2~ canceled // l_event.put("eventStatus", 1); l_event.put("eventTimezone", "India"); Uri l_eventUri; if (Build.VERSION.SDK_INT >= 8) { l_eventUri = Uri.parse("content://com.android.calendar/events"); } else { l_eventUri = Uri.parse("content://calendar/events"); } Uri l_uri = MainActivity.this.getContentResolver() .insert(l_eventUri, l_event);
    

8
投票
以防万一有人需要 C# 中的 Xamarin:

Intent intent = new Intent(Intent.ActionInsert); intent.SetData(Android.Provider.CalendarContract.Events.ContentUri); intent.PutExtra(Android.Provider.CalendarContract.ExtraEventBeginTime, Utils.Tools.CurrentTimeMillis(game.Date)); intent.PutExtra(Android.Provider.CalendarContract.EventsColumns.AllDay, false); intent.PutExtra(Android.Provider.CalendarContract.EventsColumns.EventLocation, "Location"); intent.PutExtra(Android.Provider.CalendarContract.EventsColumns.Description, "Description"); intent.PutExtra(Android.Provider.CalendarContract.ExtraEventEndTime, Utils.Tools.CurrentTimeMillis(game.Date.AddHours(2))); intent.PutExtra(Android.Provider.CalendarContract.EventsColumns.Title, "Title"); StartActivity(intent);

辅助功能:

private static readonly DateTime Jan1st1970 = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc); public static long CurrentTimeMillis(DateTime date) { return (long)(date.ToUniversalTime() - Jan1st1970).TotalMilliseconds; }
    

7
投票
Google 日历是“原生”日历应用程序。据我所知,所有手机都安装了它的一个版本,并且默认的SDK提供了一个版本。

您可以查看此

教程来使用它。


4
投票
如果您有给定的带有日期和时间的日期字符串。

例如

String givenDateString = pojoModel.getDate()/* Format dd-MMM-yyyy hh:mm:ss */



使用以下代码将带有日期和时间的事件添加到日历中

Calendar cal = Calendar.getInstance(); cal.setTime(new SimpleDateFormat("dd-MMM-yyyy hh:mm:ss").parse(givenDateString)); Intent intent = new Intent(Intent.ACTION_EDIT); intent.setType("vnd.android.cursor.item/event"); intent.putExtra("beginTime", cal.getTimeInMillis()); intent.putExtra("allDay", false); intent.putExtra("rrule", "FREQ=YEARLY"); intent.putExtra("endTime",cal.getTimeInMillis() + 60 * 60 * 1000); intent.putExtra("title", " Test Title"); startActivity(intent);
    

3
投票
你必须添加标志:

intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

否则你将导致错误:

来自 Activity 上下文外部的

startActivity()

 需要 
FLAG_ACTIVITY_NEW_TASK

    


0
投票
这是用于向日历添加事件的 Kotlin 版本:

val intent = Intent(Intent.ACTION_EDIT) intent.type = "vnd.android.cursor.item/event" intent.putExtra(CalendarContract.EXTRA_EVENT_BEGIN_TIME, startTime) intent.putExtra(CalendarContract.EXTRA_EVENT_END_TIME, endTime) intent.putExtra(CalendarContract.EXTRA_EVENT_ALL_DAY, false) intent.putExtra(CalendarContract.Events.TITLE, mTitle) startActivity(intent)
    

0
投票
Android 主要提供两种处理日历事件的方法。一个正在使用

Calendar Provider

,另一个将其交给 
system Calendar app.

Calendar Provider 为我们提供了所有的功能,包括插入、查询、更新和删除现有的日历事件。然而,这些步骤很繁琐,并且必须需要用户的运行时权限(

android.permission.READ_CALENDA

R和
android.permission.WRITE_CALENDAR
)才能读取和写入敏感的日历信息。这种方法很容易出错。

Google官方建议开发者使用第二种方法,即通过Intent将所有日历操作交给系统日历应用程序。日历应用程序在我们的应用程序请求后立即打开

甚至插入新日历

val startMillis: Long = Calendar.getInstance().run { set(2012, 0, 19, 7, 30) timeInMillis } val endMillis: Long = Calendar.getInstance().run { set(2012, 0, 19, 8, 30) timeInMillis } val intent = Intent(Intent.ACTION_INSERT) .setData(CalendarContract.Events.CONTENT_URI) .putExtra(CalendarContract.EXTRA_EVENT_BEGIN_TIME, startMillis) .putExtra(CalendarContract.EXTRA_EVENT_END_TIME, endMillis) .putExtra(CalendarContract.Events.TITLE, "Yoga") .putExtra(CalendarContract.Events.DESCRIPTION, "Group class") .putExtra(CalendarContract.Events.EVENT_LOCATION, "The gym") .putExtra(CalendarContract.Events.AVAILABILITY, CalendarContract.Events.AVAILABILITY_BUSY) .putExtra(Intent.EXTRA_EMAIL, "[email protected],[email protected]") startActivity(intent)
以下活动已开启


0
投票
Calendar beginTime = Calendar.getInstance(); beginTime.set(2012, 0, 19, 7, 30); Calendar endTime = Calendar.getInstance(); endTime.set(2012, 0, 19, 8, 30); Intent intent = new Intent(Intent.ACTION_INSERT) .setData(Events.CONTENT_URI) .putExtra(CalendarContract.EXTRA_EVENT_BEGIN_TIME, beginTime.getTimeInMillis()) .putExtra(CalendarContract.EXTRA_EVENT_END_TIME, endTime.getTimeInMillis()) .putExtra(Events.TITLE, "Yoga") .putExtra(Events.DESCRIPTION, "Group class") .putExtra(Events.EVENT_LOCATION, "The gym") .putExtra(Events.AVAILABILITY, Events.AVAILABILITY_BUSY) .putExtra(Intent.EXTRA_EMAIL, "[email protected],[email protected]"); startActivity(intent);
这是官方教程:

https://developer.android.com/guide/topics/providers/calendar-provider?hl=id#intent-insert

有效!

© www.soinside.com 2019 - 2024. All rights reserved.