AndroidでGoogleCalendarにイベントを登録する
GoogleCalendarにイベントを登録する日本語的な説明をあまりみなかったので書いてみる。
お品書き
パーミッションを忘れない。
AndroidManifest.xmlに忘れずに書いておきましょう。<uses-permission android:name="android.permission.READ_CALENDAR" /> <uses-permission android:name="android.permission.WRITE_CALENDAR" />
カレンダー情報を取得する。
カレンダーにイベントを登録するには、登録先のカレンダーがわからなければどうしようもないです。
なので、まずはカレンダー情報を取得します。
String[] projection = new String[] { "_id", "name" };//idはプライマリーキー、nameはカレンダー名 String selection = "access_level" + "=?"; String[] selectionArgs = new String[] { "700" }; Uri calendarUri = Uri.parse(calendarProveName); Cursor managedCursor = managedQuery(URI.parce("content://com.android.calendar/calendars"), projection, selection, selectionArgs, null); int[] mCalIds; String[] mCalNames; if (managedCursor.moveToFirst()) { int len = managedCursor.getCount(); mCalIds = new int[len]; mCalNames = new String[len]; int idColumnIndex = managedCursor.getColumnIndex("_id"); int nameColumnIndex = managedCursor.getColumnIndex("name"); int i = 0; do { mCalIds[i] = managedCursor.getInt(idColumnIndex); mCalNames[i] = managedCursor.getString(nameColumnIndex); i++; } while (managedCursor.moveToNext()); }
selectionでaccess_level(カレンダーの編集権限)を条件に指定しています。
"700"の場合、オーナー権限です。
イベントを登録したいのでオーナー権限があるカレンダーのみを取得しています。
これにより、祝日用のカレンダーなどが取得されなくなります。
取得したカレンダーにイベントを登録する。
下記コードは取得したカレンダーの1番目のものに対して登録しています。ContentResolver contentResolver = getContentResolver(); ContentValues cv = new ContentValues(); cv.put("calendar_id", mCalIds[0]); cv.put("title", "イベントのタイトル"); cv.put("description", "イベントの説明"); cv.put("eventLocation", "住所"); cv.put("dtstart", startDate);//ミリ秒で指定 cv.put("dtend", endDate);//ミリ秒で指定 // 通知機能を使用する場合は1を設定する。使用しない場合は省略して良い cv.put("hasAlarm", mAlert); Uri eventUri = contentResolver.insert(Uri.parse("content://com.android.calendar/events"), cv);
イベントの情報はまだ他にも設定できるけど省略。
通知情報を登録する。
通知機能を使用しない場合は、省略して良いです。insertの戻り値のURIから作成されたレコードの行番号を取得し設定します。
long rowId = Long.parseLong(eventUri.getLastPathSegment()); cv.put("event_id", rowId); cv.put("method", 1);// 通知方法を指定する cv.put("minutes", time);//分単位で指定する contentResolver.insert(Uri.parse("content://com.android.calendar/reminders"), cv);
これでカレンダーに通知付きのイベントが登録されます。
URIについて
URIの指定がAndroid2.2とそれ以前で違います。- Android2.2
calendar :"content://com.android.calendar/calendars"
event :"content://com.android.calendar/events"
reminder:"content://com.android.calendar/reminders"
- Android2.1まで
calendar :"content://calendar/calendars"
event :"content://calendar/events"
reminder:"content://calendar/reminders"
サンプル
下記URLにサンプルコードを置いています。
https://github.com/gensuke/SampleCalendar