Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

讀取與修改 Android 系統日曆行程

編輯:關於 Android 程式設計

先提醒一件重要的事:Android 的日曆只有真實設備才有,模擬器上並不存在,所以測試環境務必使用真機。

一、宣告權限

日曆屬於系統內建應用,讀寫它必須先申請權限。在 AndroidManifest.xml 中加入以下兩行(一個讀、一個寫):

<!-- get calendar read and write permission -->
<uses-permission android:name="android.permission.READ_CALENDAR" />
<uses-permission android:name="android.permission.WRITE_CALENDAR" />

二、處理版本差異

日曆的 ContentProvider URI 在 2.2 之後有過變動,因此需要做版本判斷:

// 為了相容不同版本的日曆,2.2 以後 URL 發生改變
private static String calanderEventURL = "";
static {
    if (Integer.parseInt(Build.VERSION.SDK) >= 8) {
        calanderEventURL = "content://com.android.calendar/events";
    } else {
        calanderEventURL = "content://calendar/events";
    }
}

三、讀取行程

ContentResolver cr = context.getContentResolver();
Uri uri = Uri.parse(calanderEventURL);
Cursor cursor = cr.query(uri, null, null, null, null);
while (cursor.moveToNext()) {
    CalendarEvent cde = new CalendarEvent();
    cde.setCalendar_id(cursor.getString(cursor.getColumnIndex(Events.CALENDAR_ID)));
    cde.setTitle(cursor.getString(cursor.getColumnIndex(Events.TITLE)));
    cde.setDtstart(cursor.getString(cursor.getColumnIndex(Events.DTSTART)));
    cde.setDtend(cursor.getString(cursor.getColumnIndex(Events.DTEND)));
    cde.setDuration(cursor.getString(cursor.getColumnIndex(Events.DURATION)));
    cde.setRrule(cursor.getString(cursor.getColumnIndex(Events.RRULE)));
    cde.setEventTimezone(cursor.getString(cursor.getColumnIndex(Events.EVENT_TIMEZONE)));
    calendarEvents.add(cde);
}
cursor.close();

四、寫入行程

新增行程時,有幾個欄位屬於必填,範例只示範這幾項:

ContentValues values = new ContentValues();
values.put(Events.CALENDAR_ID, calendarId);   // 所屬日曆 ID,必填
values.put(Events.TITLE, "測試行程");          // 標題,必填
values.put(Events.DTSTART, startTime);         // 開始時間(毫秒),必填
values.put(Events.DTEND, endTime);             // 結束時間(毫秒),必填
values.put(Events.EVENT_TIMEZONE, TimeZone.getDefault().getID());

context.getContentResolver().insert(Uri.parse(calanderEventURL), values);

實務上容易踩到的幾個點:Android 4.0 以後,寫入 Events 之前必須先確定要掛在哪個 calendar_id 底下,若裝置上沒有任何可寫日曆(例如未登入帳號),insert 會直接失敗,需先透過 Calendars URI 查詢或建立;此外修改與刪除行程要用 ContentResolver.update / delete 搭配 event 的 _ID,而非重新 insert;最後,若同時存在多個帳號的日曆,記得用 selection 條件篩選,否則會撈到意料之外的資料。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved