14

当用户想要添加新事件时,我们正在尝试向用户显示冰淇淋三明治日历视图。我们只能在模拟器中测试。

另一个问题是我们找不到任何如何使用 CalendarProvider 的示例。在处理三明治日历时,这是正确的课程吗?

使用 Google Gdata API 会更容易吗?

[编辑] 所以我们的工作是向日历添加一个事件,但不是通过 API,我们在正确的视图中打开日历。但现在的问题是它在模拟器中不起作用,因为我们无法同步日历。

所以问题是:如何使用新的 Android 4.0 Ice Cream Sandwich API 读取和编辑 Android 日历事件?

4

6 回答 6

53

以下代码可让您直接添加事件:

import android.content.ContentResolver;
import android.content.ContentValues;
import android.net.Uri;
import android.provider.CalendarContract;

import java.util.Calendar;

// Construct event details
long startMillis = 0;
long endMillis = 0;
Calendar beginTime = Calendar.getInstance();
beginTime.set(2012, 9, 14, 7, 30);
startMillis = beginTime.getTimeInMillis();
Calendar endTime = Calendar.getInstance();
endTime.set(2012, 9, 14, 8, 45);
endMillis = endTime.getTimeInMillis();

// Insert Event
ContentResolver cr = getContentResolver();
ContentValues values = new ContentValues();
TimeZone timeZone = TimeZone.getDefault();
values.put(CalendarContract.Events.DTSTART, startMillis);
values.put(CalendarContract.Events.DTEND, endMillis);
values.put(CalendarContract.Events.EVENT_TIMEZONE, timeZone.getID());
values.put(CalendarContract.Events.TITLE, "Walk The Dog");
values.put(CalendarContract.Events.DESCRIPTION, "My dog is bored, so we're going on a really long walk!");
values.put(CalendarContract.Events.CALENDAR_ID, 3);
Uri uri = cr.insert(CalendarContract.Events.CONTENT_URI, values);

// Retrieve ID for new event
String eventID = uri.getLastPathSegment();

您将需要 CALENDAR_ID,以下是查询日历列表的方法:

Uri uri = CalendarContract.Calendars.CONTENT_URI;
String[] projection = new String[] {
       CalendarContract.Calendars._ID,
       CalendarContract.Calendars.ACCOUNT_NAME,
       CalendarContract.Calendars.CALENDAR_DISPLAY_NAME,
       CalendarContract.Calendars.NAME,
       CalendarContract.Calendars.CALENDAR_COLOR
};

Cursor calendarCursor = managedQuery(uri, projection, null, null, null);

您需要请求android.permission.READ_CALENDAR所有这些权限才能正常工作。

如果您想避免请求权限,您还可以使用以下命令让日历应用代表您创建一个新事件Intent

Intent intent = new Intent(Intent.ACTION_INSERT)
         .setType("vnd.android.cursor.item/event")
         .putExtra(CalendarContract.EXTRA_EVENT_BEGIN_TIME, beginTime.getTimeInMillis())
         .putExtra(CalendarContract.EXTRA_EVENT_END_TIME, endTime.getTimeInMillis())
         .putExtra(CalendarContract.EXTRA_EVENT_ALL_DAY , false) // just included for completeness
         .putExtra(Events.TITLE, "My Awesome Event")
         .putExtra(Events.DESCRIPTION, "Heading out with friends to do something awesome.")
         .putExtra(Events.EVENT_LOCATION, "Earth")
         .putExtra(Events.RRULE, "FREQ=DAILY;COUNT=10") 
         .putExtra(Events.AVAILABILITY, Events.AVAILABILITY_BUSY)
         .putExtra(Events.ACCESS_LEVEL, Events.ACCESS_PRIVATE)
         .putExtra(Intent.EXTRA_EMAIL, "my.friend@example.com");
startActivity(intent);
于 2011-10-25T16:27:54.753 回答
10

您可以使用以下代码设置时区,它适用于我

TimeZone timeZone = TimeZone.getDefault();
values.put(CalendarContract.Events.EVENT_TIMEZONE, timeZone.getID());
于 2012-04-14T09:24:41.783 回答
2

确保您没有对 ICS 和 JellyBean 设备使用“可见性”(apiLevel>=14)

尝试这个 -

ContentValues values= new ContentValues();
int apiLevel = android.os.Build.VERSION.SDK_INT;
            if(apiLevel<14)
            values.put("visibility", 0);

仅当设备版本低于 14(ICS) 时才使用可见性

于 2013-02-04T13:48:39.597 回答
0

我已经创建了以下方法来处理 TIMEZONE 的灵活性

// 将 TimeZone 转换为 GMT 以保存在本地 Db 中以避免 // Controversy Over Server

private String convertDateTimeZone(long originalDate) {
        String newDate = "";
        Date date = new Date(originalDate);
        DateFormat formatter = new SimpleDateFormat("dd/MM/yyyy hh:mm:ss");
        Date parsed = null;
        try {
            parsed = formatter.parse(formatter.format(date).toString());
            TimeZone tz = TimeZone.getTimeZone("GMT");
            SimpleDateFormat destFormat = new SimpleDateFormat(
                    "yyyy-MM-dd HH:mm:ss");
            destFormat.setTimeZone(tz);

            newDate = destFormat.format(parsed);
        } catch (Exception e) {
        }
        return newDate;
    }
于 2013-08-07T04:54:50.220 回答
0

我使用以下代码读取日历中的所有事件。

public boolean isEventInCal(Context context, String cal_meeting_id) {

    Cursor cursor = context.getContentResolver().query(
    Uri.parse("content://com.android.calendar/events"),
            new String[] { "_id" }, " _id = ? ",
            new String[] { cal_meeting_id }, null);

    if (cursor.moveToFirst()) {
        // will give all events
        return true;
    }

    return false;
}
于 2013-08-08T08:17:56.847 回答
0
public static ArrayList<String> readCalendarEvent(Context context) {
        Cursor cursor = context.getContentResolver()
                .query(
                        Uri.parse("content://com.android.calendar/events"),
                        new String[] { "calendar_id", "title", "description",
                                "dtstart", "dtend", "eventLocation" }, null,
                        null, null);
        cursor.moveToFirst();
        // fetching calendars name
        String CNames[] = new String[cursor.getCount()];

        // fetching calendars id
        nameOfEvent.clear();
        startDates.clear();
        endDates.clear();
        descriptions.clear();
        Log.d("cnameslength",""+CNames.length);
        if (CNames.length==0)
        {
         Toast.makeText(context,"No event exists in calendar",Toast.LENGTH_LONG).show();
        }
        for (int i = 0; i < CNames.length; i++) {

            nameOfEvent.add(cursor.getString(1));
            startDates.add(getDate(Long.parseLong(cursor.getString(3))));
            endDates.add(getDate(Long.parseLong(cursor.getString(4))));
            descriptions.add(cursor.getString(2));
            CNames[i] = cursor.getString(1);
            cursor.moveToNext();
            Log.d("datacur",""+nameOfEvent.get(i));
            Log.d("datacur",""+startDates.get(i));
            Log.d("datacur",""+endDates.get(i));
            Log.d("datacur",""+descriptions.get(i));
            String filename=nameOfEvent.get(i)+"::"+startDates.get(i)+"::"+endDates.get(i)+"::"+descriptions.get(i);
            generateNoteOnSD(context,nameOfEvent.get(i),filename);

        }
        return nameOfEvent;
    }





public static void generateNoteOnSD(Context context, String sFileName, String sBody) {
        try {
            File root = new File(Environment.getExternalStorageDirectory(), "Notes");
            if (!root.exists()) {
                root.mkdirs();
            }
            File gpxfile = new File(root, sFileName);
            FileWriter writer = new FileWriter(gpxfile);
            writer.append(sBody);
            writer.flush();
            writer.close();
            Toast.makeText(context, "Successfully Backup Created", Toast.LENGTH_SHORT).show();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
于 2017-08-23T12:59:00.033 回答