代码与范例:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 |
import android.app.Activity; import android.content.ContentValues; import android.database.Cursor; import android.net.Uri; import android.os.Build; import android.os.Bundle; import android.text.format.DateUtils; import android.widget.TextView; public class CalendarTestActivity extends Activity { private TextView tv;// 用于屏幕文字显示的TextView private String temp;// 用以记录TextView的文本内容 public String AUTHORITY;// 用以适应不同的Android系统版本下日历的内容提供器Uri的不同 @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); final int sdkVersion = Build.VERSION.SDK_INT; //获取设备的Android系统版本号 // 8=Build.VERSION_CODES.FROYO if (sdkVersion < 8) { //Android从版本2.2起Calendar的Uri发生了变化,必须注意 AUTHORITY = "calendar"; } else { AUTHORITY = "com.android.calendar"; } temp = ""; Cursor cursor = getContentResolver().query(Uri.parse("content://" + AUTHORITY + "/calendars"), new String[] { "_id", "displayName" }, "selected=1", null, null); if (cursor != null && cursor.moveToFirst()) { String[] calNames = new String[cursor.getCount()]; int[] calIds = new int[cursor.getCount()]; for (int i = 0; i < calNames.length; i++) { calIds[i] = cursor.getInt(0); calNames[i] = cursor.getString(1); //将获取的日历名称信息加入字符串变量temp temp += Integer.toString(calIds[i]); temp += " "; temp += calNames[i]; temp += "\n"; cursor.moveToNext(); } cursor.close(); if (calIds.length > 0) { //可以在此进行操作 } } tv = (TextView) findViewById(R.id.con); tv.setText(temp); } //添加日历项目 public void insert(int calIDs) { int cal_id = calIDs; ContentValues cv = new ContentValues(); cv.put("calendar_id", cal_id); cv.put("title", "Judy's birthday"); cv.put("description", "Time to celebrate Judy's birthday."); cv.put("eventLocation", "KFC, SH"); cv.put("dtstart", System.currentTimeMillis()); cv.put("dtend", System.currentTimeMillis() + DateUtils.DAY_IN_MILLIS); cv.put("allDay", 1); cv.put("hasAlarm", 1); getContentResolver().insert(Uri.parse("content://" + AUTHORITY + "/events"), cv); } } |
说明:Android中内容提供器(ContentProvider)有着广泛的应用,Google账户同步的日历也将数据储存在相应的内容提供器中。这里是日历内容提供器的一个简单范例,可以获取日历的名称,并提供了一个添加日历项目的方法。