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);
}
}