2012年1月12日 星期四

Android 開發筆記 - 取得 Calendar Events 與相關筆記

最近摸到一台變形金剛,順便學習一些簡單的東西,這次目標就是取得 Calendar Events,對整個 Android 系統來說,有不少 App 都提供讓人存取的功能,在此以 Calendar 為例。


另外一提的,很多資料都是用 SQLite 格式儲存在系統裡頭,可以透過 DDMS 或其他 shell 方式瀏覽或取出 db 檔案(/data/data/com.android.providers.calendar/databases/calendar.db),接著可以用 Firefox Plugin - SQLite Manager 去查看也挺方便喔。(此動作需要root權限)


程式碼:


package tw.study.provider.calendar;


import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Hashtable;


import android.app.Activity;
import android.content.ContentResolver;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.text.format.DateUtils;
import android.util.Log;


public class CalendarEventProviderActivity extends Activity {
    /** Called when the activity is first created. */
    private String tagReport = "CalendarProviderActivity";
    private ArrayList<String> calendarEvents = new ArrayList<String>();
    private Hashtable<String,String> accountInfo = new Hashtable<String,String>();
    private String URI_CALENDAR_BASE = "content://com.android.calendar/calendars";
    private String URI_CALENDAR_RANGE_QUERY = "content://com.android.calendar/instances/when"; // content://com.android.calendar/instances/when/begin/end
    private SimpleDateFormat TimeFormat = new SimpleDateFormat("HH:mm");

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        if(getInfoFromCalendarDB()>0) {
                // do something via calendarEvents
        }
    }

    private int getInfoFromCalendarDB() {
        long dateRangeBegin = new Date().getTime();
        Date today = new Date(dateRangeBegin + DateUtils.DAY_IN_MILLIS);
        long dateRangeEnd=new Date(today.getYear(),today.getMonth(),today.getDate()).getTime();
        
        Log.e(tagReport,"date range from '"+dateRangeBegin +"' to '"+dateRangeEnd+"'");

        ContentResolver contentResolver = this.getContentResolver();
        Cursor accountInfoCursor = contentResolver.query(Uri.parse(URI_CALENDAR_BASE), (new String[] { "_id", "displayName", "selected", "_sync_account" }), null, null, null);
        while (accountInfoCursor.moveToNext()) {
            String _id = accountInfoCursor.getString(0);
            String displayName = accountInfoCursor.getString(1);
            String syncAccount = accountInfoCursor.getString(3);
            if( !accountInfoCursor.getString(2).equals("0") ) { // selected => enable
                accountInfo.put( syncAccount, displayName ); // use for check or display the account name
                accountInfo.put( _id, displayName );
            }
        }

        // show all columns
        String targetQuery = URI_CALENDAR_RANGE_QUERY+"/"+dateRangeBegin+"/"+dateRangeEnd;
        Log.e(tagReport,"Range Query:"+targetQuery);
        Cursor eventCursor = contentResolver.query(Uri.parse(targetQuery), null, null, null, "startDay ASC, startMinute ASC");
        for( String c : eventCursor.getColumnNames() ) 
            Log.e(tagReport,"column name:"+c);

        // add all events
        calendarEvents.clear();
        eventCursor = contentResolver.query(Uri.parse(URI_CALENDAR_RANGE_QUERY+"/"+dateRangeBegin+"/"+dateRangeEnd), new String[] { "title", "begin", "end", "calendar_id"}, null,null,"startDay ASC, startMinute ASC");
        while (eventCursor.moveToNext()) {
            String title = eventCursor.getString(0);
            Long begin = eventCursor.getLong(1);
            Long end = eventCursor.getLong(2);
            String accountId = eventCursor.getString(3);
                if( accountInfo.containsKey(accountId) ) { // skip the account which is not enabled
                calendarEvents.add("["+TimeFormat.format(new Date(begin))+"-"+TimeFormat.format(new Date(end))+"] "+title+"("+accountInfo.get(accountId)+")" );
            }
        }
        return calendarEvents.size();
    }


AndroidManifest.xml:


<uses-permission android:name="android.permission.READ_CALENDAR"/>


輸出:


date range from '1326368807153' to '1326384000000'
Range Query:content://com.android.calendar/instances/when/1326368807153/1326384000000
column name:originalEvent
column name:ownerAccount
column name:endDay
column name:visibility
column name:endMinute
column name:rrule
column name:event_id
column name:lastDate
column name:hasAlarm
column name:guestsCanModify
column name:transparency
column name:rdate
column name:exrule
column name:guestsCanSeeGuests
column name:title
column name:dtstart
column name:selected
column name:timezone
column name:_id
column name:hasAttendeeData
column name:commentsUri
column name:startDay
column name:description
column name:htmlUri
column name:end
column name:startMinute
column name:hasExtendedProperties
column name:calendar_id
column name:eventLocation
column name:dtend
column name:access_level
column name:allDay
column name:organizer
column name:originalAllDay
column name:deleted
column name:url
column name:begin
column name:originalInstanceTime
column name:duration
column name:color
column name:selfAttendeeStatus
column name:guestsCanInviteOthers
column name:exdate
column name:eventStatus
column name:eventTimezone


沒有留言:

張貼留言