programing tip

Android에서 캘린더 일정을 추가하는 방법은 무엇입니까?

itbloger 2020. 6. 9. 08:19
반응형

Android에서 캘린더 일정을 추가하는 방법은 무엇입니까?


나는 안드로이드에서 속도를 높이고 있으며 오늘 프로젝트 회의에서 누군가 안드로이드에 기본 캘린더 앱이 없으므로 사용자는 원하는 캘린더 앱만 사용한다고 말했다.

이것이 사실입니까? 그렇다면 프로그래밍 방식으로 이벤트를 사용자의 캘린더에 어떻게 추가합니까? 모두 공유하는 공통 API가 있습니까?

그 가치가 있다면 Android 2.x를 타겟팅하고있을 것입니다.


프로그래밍 방식으로 이벤트를 사용자의 캘린더에 추가하려면 어떻게합니까?

어떤 달력?

모두 공유하는 공통 API가 있습니까?

아니요, Windows 캘린더 앱용으로 "모두 공유하는 공통 API"가 있습니다. 일반적인 데이터 형식 (예 : iCalendar)과 인터넷 프로토콜 (예 : CalDAV)이 있지만 공통 API는 없습니다. 일부 캘린더 앱은 API도 제공하지 않습니다.

통합하려는 특정 캘린더 애플리케이션이있는 경우 개발자에게 문의하여 API를 제공하는지 확인하십시오. 예를 들어 Mayra가 인용 한 Android 오픈 소스 프로젝트의 캘린더 애플리케이션은 문서화되고 지원되는 API를 제공하지 않습니다. 구글은 개발자들에게 Mayra cite 튜토리얼에 기술 된 기술을 사용하지 말라고 명시 적으로 언급했다.

다른 옵션은 해당 인터넷 일정에 이벤트를 추가하는 것입니다. 예를 들어 Android 오픈 소스 프로젝트에서 캘린더 애플리케이션에 이벤트를 추가하는 가장 좋은 방법은 적절한 GData API를 통해 사용자의 Google 캘린더에 이벤트를 추가하는 것입니다.


최신 정보

Android 4.0 (API 레벨 14)에을 추가했습니다 CalendarContract ContentProvider.


코드에서 이것을 시도하십시오 :

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

이 API를 코드에서 사용하십시오. 이벤트, 알림이 포함 된 이벤트 및 미팅이있는 이벤트를 삽입하는 데 도움이됩니다.이 API는 플랫폼 2.1 이상에서 작동합니다. content : // com 대신 2.1 이하를 사용하는 사용자 .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", "yyyy@gmail.com");// 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;

}

아래 코드를 사용하여 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, "rowan@example.com,trevor@example.com");
         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);
        }

그것이 도움이되기를 바랍니다 .....


Android 버전 4.0 부터 사용 가능한 캘린더 공급자 와 상호 작용하기 위해 공식 API 및 의도를 사용할 수 있습니다 .


Google 캘린더는 "기본"캘린더 앱입니다. 내가 아는 한, 모든 전화에는 설치된 버전이 있으며 기본 SDK는 버전을 제공합니다.

학습서 를 사용 하여이 학습서확인 하십시오.


이 시도 ,

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

Just in case if someone needs this for Xamarin in c#:

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

Helper Functions:

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

if you have a given Date string with date and time .

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

use the following code to add an event with date and time to the calendar

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

you have to add flag:

intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

or you will cause error with:

startActivity() from outside of an Activity context requires the FLAG_ACTIVITY_NEW_TASK

참고URL : https://stackoverflow.com/questions/3721963/how-to-add-calendar-events-in-android

반응형