Androidでカレンダーイベントを追加する方法


159

私はAndroidに慣れてきました。今日のプロジェクト会議で、誰かがAndroidにはネイティブカレンダーアプリがないため、ユーザーは好きなカレンダーアプリを使用できると言っています。

これは本当ですか、そうであれば、プログラムでユーザーのカレンダーにイベントを追加するにはどうすればよいですか?彼らが共有する共通のAPIはありますか?

価値があるのは、おそらくAndroid 2.xをターゲットにしていることでしょう。


oriharelがあなたのタスクを達成するためのコードを提供するので、おそらくoriharelの答えを受け入れる必要があります。
jww

1
@SumitSharmaあなたのリンクはもう機能していないようです-自動インストールダイアログでかなり疑わしいようです。
修正

回答:


17

プログラムでユーザーのカレンダーにイベントを追加するにはどうすればよいですか?

どのカレンダー?

彼らが共有する共通のAPIはありますか?

いいえ、Windowsカレンダーアプリ用の「共通のAPI」があるだけです。いくつかの一般的なデータ形式(iCalendarなど)とインターネットプロトコル(CalDAVなど)がありますが、一般的なAPIはありません。一部のカレンダーアプリは、APIさえ提供していません。

統合したい特定のカレンダーアプリケーションがある場合は、その開発者に連絡して、APIを提供しているかどうかを確認してください。したがって、たとえば、メイラが引用しているAndroidオープンソースプロジェクトのカレンダーアプリケーションは、ドキュメント化されサポートされているAPIを提供していません。Googleは、メイラが引用しているチュートリアルで概説されている手法使用しないように開発者に明示的に指示しています

別のオプションは、問題のインターネットカレンダーにイベントを追加することです。たとえば、Androidオープンソースプロジェクトからカレンダーアプリケーションにイベントを追加する最良の方法は、適切なGData APIを介してユーザーのGoogleカレンダーにイベントを追加することです。


更新

Android 4.0(APIレベル14)にが追加されましたCalendarContract ContentProvider


6
特定のカレンダーをターゲットにしたくない-ユーザーの便宜のために、ユーザーが使用しているカレンダーにイベントを追加できるようにしたいだけです。私たちのアプリは、プロの会議や会議を開催するウェブサイトへのインターフェースを提供します。したがって、誰かが1つにサインアップした場合、それを自分のカレンダーにポップするとよいでしょう。
Peter Nelson

3
@Peter Nelson:「特定のカレンダーをターゲットにしたくない-ユーザーの便宜のために、ユーザーが使用しているカレンダーにイベントを追加できるようにしたいだけだ」-Androidでできることは、Windowsでできることと同じです。どちらのプラットフォームでも、「ユーザーが使用しているカレンダー」はわかりません。どちらのプラットフォームにも、そのようなカレンダーアプリケーションを操作するためのユニバーサルAPIはありません。
CommonsWare

22
なぜWindowsと比較し続けるのかわかりません-私の知っている人は皆、自分の電話を使ってスケジュールや予定を整理しています-PCでそれを実行している人は誰も知りません-おそらく世代の問題でしょう。しかし、Androidではそれができないのです。ありがとう。
Peter Nelson

5
@ピーター・ネルソン:同じ仮定をしているので、Windowsと比較し続けます。多くの開発者は、Windowsで「ユーザーが使用しているカレンダーにイベントを追加」できると考えています。なぜなら、誰もがOutlookを使用していると考えているため、「カレンダーは1つ」しかないためです。
CommonsWare

1
@Yar:「メインのAndroid電話カレンダー。どのAndroid電話にもあります。」-そのアプリを搭載していないすべてのAndroidデバイスを除きます。たとえば、多くのHTCデバイスにはそのアプリがなく、左側に6インチのHTC DROID Incredibleなどの独自のカレンダーアプリがあります。デバイスメーカーは、カレンダーアプリ(または他のほぼすべてのアプリ)を独自の実装に置き換えることを歓迎します。
CommonsWare、2011年

290

あなたのコードでこれを試してください:

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

6
私はこのソリューションがとても好きです。主に、ユーザーが自分のカレンダーを選択するように強制するためです(複数ある場合)。
Sebastian Roth

2
これをandroid 2.2と互換性のあるものにする方法は?
Srikanth Pai 2012

13
一部のデバイスではsetType(string)を使用するとクラッシュするため、setTypeではなく.setData(CalendarContract.Events.CONTENT_URI)を使用する必要があります。
Informatic0re

4
ここでの完全なチュートリアル:code.tutsplus.com/tutorials/… タイプミスを回避するために定数を使用することをお勧めします;)
Adrien Cadet

7
このコードは、別の(カレンダー)アプリにデータを送信するようアプリに指示し、アプリはそのデータを使用して新しいカレンダーイベントを追加します。アプリはカレンダーデータの書き込みや読み取りを行わないため、マニフェストに権限は必要ありません。
2015年

66

この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;

}

4
私は追加event.put("eventTimezone", "UTC/GMT +2:00")して削除event.put("visibility", 3)しましたが、event.put("transparency", 0)うまくいきました
validcat '25

1
タイムゾーンエラーが発生する可能性があります。これとその作品を追加しますeventValues.put( "eventTimezone"、TimeZone.getDefault()。getID());
Cüneyt

2
私は取得していますandroid.database.sqlite.SQLiteExceptionラインでUri reminderUri = curActivity.getApplicationContext().getContentResolver().insert(Uri.parse(reminderUriString), reminderValues);
Sibidharan

1
しかし、values.put( "rrule"、 "FREQ = DAILY");を設定した場合は1つです。endDateを設定しますが、機能しません。イベントは終了日までのすべての日に設定されます。@AmitabhaBiswas
urvi joshi

1
values.put(CalendarContract.Reminders.CALENDAR_ID、1); values.put(CalendarContract.Reminders.TITLE、 "Routine Everyday1"); values.put(CalendarContract.Reminders.DTSTART、millisecondsTimesEveryday); values.put(CalendarContract.Reminders.HAS_ALARM、true); values.put( "rrule"、 "FREQ = DAILY"); // UNTIL = 1924885800000 values.put(CalendarContract.Reminders.DTEND、EndtimeInMilliseconds); @AmitabhaBiswas
urvi joshi

57

私は以下のコードを使用しました。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);
        }

それが役に立てば幸い...


Build.VERSION.SDK_INT> 14について、デフォルトのリマインダーを60分間追加するにはどうすればよいですか。また、リマインダーのIDを取得するにはどうすればよいですか。ありがとう
user1796624

こんにちは、編集可能なカレンダーフィールドを表示する画面を変更できるかどうか(ビューの一部の外観を変更するなど)はどうでしょうか。
user1950599 2013

@ user1950599間違いなく。インテントは別のアプリケーションからアクティビティを開始し、それとの唯一の相互作用は、インテントを介して送信するデータです。
Pijusn


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がバージョンを提供しています。

あなたはそれを扱うためにこのチュートリアルをチェックするかもしれません。


7

これを試して 、

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

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

または、次のエラーが発生します。

startActivity() アクティビティコンテキストの外側から FLAG_ACTIVITY_NEW_TASK

弊社のサイトを使用することにより、あなたは弊社のクッキーポリシーおよびプライバシーポリシーを読み、理解したものとみなされます。
Licensed under cc by-sa 3.0 with attribution required.