2014年1月10日 星期五

Read calendar events

Many developers would like to check the user's calendar for events. In our example we are checking if the user is in the middle of something right now, if so we are printing a simple message.

This will work with android 2.1 and up. It will also work for all day events.

Please note that the android emulator doesn't have calendar installed! 
I test my projects on my android phone.

On with some code:

CalendarContract.Events.CONTENT_URI = "content://com.android.calendar/events"


         Context context = getApplicationContext();    
         ContentResolver contentResolver = context.getContentResolver();  
          //get current time  
              //needed to compare with event time from calendar  
              //all times are UTC so with one value we can check the date too  
              //see wiki for UTC time  
         //current time  
          long ntime = System.currentTimeMillis();  
              //read from the first calendar  
              Cursor cursr = contentResolver.query(Uri.parse("content://com.android.calendar/events"), new String[]{ "calendar_id", "title", "description", "dtstart", "dtend", "eventLocation" }, "calendar_id=1", null, null);       
              cursr.moveToFirst();  
          String[] CalNames = new String[cursr.getCount()];  
          int[] CalIds = new int[cursr.getCount()];  
          for (int i = 0; i < CalNames.length; i++) {  
            CalIds[i] = cursr.getInt(0);             
            CalNames[i] = "Event"+cursr.getInt(0)+": \nTitle: "+ cursr.getString(1)+"\nDescription: "+cursr.getString(2)+"\nStart Date: "+cursr.getLong(3)+"\nEnd Date : "+cursr.getLong(4)+"\nLocation : "+cursr.getString(5);  
            long StartTime = cursr.getLong(3);  
            long EndTime = cursr.getLong(4);  
            //do compare here  
            //if we are on the middle of something stop checking and leave the loop  
            if ((StartTime<ntime)&&(ntime<EndTime)) {  
                 System.out.println("In the middle of something");  
                 break;  
            }                  
            cursr.moveToNext();  
          }  
          cursr.close();  

沒有留言:

張貼留言

Related Posts Plugin for WordPress, Blogger...