我通过以下代码段触发日历事件的创建:
Intent intent = new Intent(Intent.ACTION_INSERT);
intent.setData(CalendarContract.Events.CONTENT_URI);
startActivity(intent);
但我想指定应该使用哪个日历来创建事件(即在事件创建屏幕中设置日历下拉列表的初始值)。
我试图提供ACCOUNT_TYPE
、ACCOUNT_NAME
和CALENDAR_ID
intent.putExtra(CalendarContract.Events.ACCOUNT_TYPE, accountType);
intent.putExtra(CalendarContract.Events.ACCOUNT_NAME, accountName);
intent.putExtra(CalendarContract.Events.CALENDAR_ID, calendarId);
但它对日历下拉初始值没有影响。
是否可以在事件创建意图中指定日历?
,没有可靠的方法可以仅用Intent
来实现这一点。您可能会遇到各种可能支持也可能不支持此功能的日历应用程序。
如果您不介意用户无法更改日历,您可以通过一个简单的技巧来实现这一点:
只需在您想要的日历中创建一个"占位符"事件(如 Android 开发人员指南中所述),然后改为为此事件触发Intent.ACTION_EDIT
Intent
。
以下是一些(未经测试的)代码来显示它是如何工作的:
ContentResolver cr = getContentResolver();
ContentValues values = new ContentValues();
// provide an initial time
long now=System.currentTimeMillis();
values.put(Events.DTSTART, now);
values.put(Events.DTEND, now+3600000);
values.put(Events.TITLE, "");
values.put(Events.CALENDAR_ID, calendarId);
values.put(Events.EVENT_TIMEZONE, TimeZone.getDefault().getID());
// create the "placeholder" event
Uri uri = cr.insert(Events.CONTENT_URI, values);
// get the event ID that is the last element in the Uri
long eventId = Long.parseLong(uri.getLastPathSegment());
// launch the editor to edit the "placeholder" event
Intent intent = new Intent(Intent.ACTION_EDIT);
intent.setData(ContentUris.withAppendedId(CalendarContract.Events.CONTENT_URI, eventId));
startActivityForResult(intent, 0);
编辑Intent
可能不会返回一个状态,告诉您事件是否已保存,或者用户是否在未保存的情况下关闭了编辑器。因此,您应该回读事件并检查它是否已被用户修改,如果尚未更改,则将其删除。
使用这种简单的方法添加事件很简单。
public void onAddEventClicked(View view) {
Intent intent = new Intent(Intent.ACTION_INSERT);
intent.setType("vnd.android.cursor.item/event");
Calendar cal = Calendar.getInstance();
long startTime = cal.getTimeInMillis();
long endTime = cal.getTimeInMillis() + 60 * 60 * 1000;
intent.putExtra(CalendarContract.EXTRA_EVENT_BEGIN_TIME, startTime);
intent.putExtra(CalendarContract.EXTRA_EVENT_END_TIME, endTime);
intent.putExtra(CalendarContract.EXTRA_EVENT_ALL_DAY, true);
//This is Information about Calender Event.
intent.putExtra(Events.TITLE, "Siddharth Birthday");
intent.putExtra(Events.DESCRIPTION, "This is a description");
intent.putExtra(Events.EVENT_LOCATION, "My Guest House");
intent.putExtra(Events.RRULE, "FREQ=YEARLY");
startActivity(intent);
}
使用以下代码片段调用默认日历事件。
Intent intent = new Intent(Intent.ACTION_INSERT_OR_EDIT);
intent.setType("vnd.android.cursor.item/event");
startActivity(intent);
以下代码包可用于将信息传递给日历意图。
intent.putExtra(CalendarContract.EXTRA_EVENT_BEGIN_TIME, startTime);
intent.putExtra(CalendarContract.EXTRA_EVENT_END_TIME,endTime);
intent.putExtra(CalendarContract.EXTRA_EVENT_ALL_DAY, true);
intent.putExtra(Events.TITLE, "Neel Birthday");
intent.putExtra(Events.DESCRIPTION, "This is a sample description");
intent.putExtra(Events.EVENT_LOCATION, "My Guest House");
intent.putExtra(Events.RRULE, "FREQ=YEARLY");
愿它能帮助你:)谢谢。
来源:如何在Android中将事件添加到设备日历
你也可以检查这个。将事件添加到用户的日历