Java 在安卓4中,如何将日历事件添加到默认日历中,无需任何提示?

Java 在安卓4中,如何将日历事件添加到默认日历中,无需任何提示?,java,android,android-calendar,Java,Android,Android Calendar,我想在android 4+中以编程方式(直接)添加日历事件。这是否可以在emulator上进行测试?我没有安卓手机。一些示例代码将不胜感激。我读过android开发者的日历提供商,但我很困惑。如何将事件添加到用户的默认日历?我不需要同步 编辑:我不想启动事件添加意图。相反,我想完全从代码中添加它们,而不是启动另一个活动。我需要能够在模拟器上测试事件是否会添加到设备默认用户的主日历中。如何设置模拟器以查看用户的默认日历?我相信您要查找的部分是。在本节中,它描述了如何为要添加的事件创建意图,然后em

我想在android 4+中以编程方式(直接)添加日历事件。这是否可以在emulator上进行测试?我没有安卓手机。一些示例代码将不胜感激。我读过android开发者的日历提供商,但我很困惑。如何将事件添加到用户的默认日历?我不需要同步


编辑:我不想启动事件添加意图。相反,我想完全从代码中添加它们,而不是启动另一个活动。我需要能够在模拟器上测试事件是否会添加到设备默认用户的主日历中。如何设置模拟器以查看用户的默认日历?

我相信您要查找的部分是。在本节中,它描述了如何为要添加的事件创建意图,然后emulator上的默认日历程序将响应并添加它。您可能需要设置一个虚拟配置文件,以便日历程序在您确实希望看到它收到正确信息时启动


代码来源:

Calendar beginTime = Calendar.getInstance();
beginTime.set(2012, 0, 19, 7, 30);
Calendar endTime = Calendar.getInstance();
endTime.set(2012, 0, 19, 8, 30);
Intent intent = new Intent(Intent.ACTION_INSERT)
    .setData(Events.CONTENT_URI)
    .putExtra(CalendarContract.EXTRA_EVENT_BEGIN_TIME, beginTime.getTimeInMillis())
    .putExtra(CalendarContract.EXTRA_EVENT_END_TIME, endTime.getTimeInMillis())
    .putExtra(Events.TITLE, "Yoga")
    .putExtra(Events.DESCRIPTION, "Group class")
    .putExtra(Events.EVENT_LOCATION, "The gym")
    .putExtra(Events.AVAILABILITY, Events.AVAILABILITY_BUSY)
    .putExtra(Intent.EXTRA_EMAIL, "rowan@example.com,trevor@example.com");
startActivity(intent);
这是我最终成功的一个工作示例:

ContentResolver cr = ctx.getContentResolver();
ContentValues values = new ContentValues();

values.put(CalendarContract.Events.DTSTART, dtstart);
values.put(CalendarContract.Events.TITLE, title);
values.put(CalendarContract.Events.DESCRIPTION, comment);

TimeZone timeZone = TimeZone.getDefault();
values.put(CalendarContract.Events.EVENT_TIMEZONE, timeZone.getID());

// Default calendar
values.put(CalendarContract.Events.CALENDAR_ID, 1);

values.put(CalendarContract.Events.RRULE, "FREQ=DAILY;UNTIL="
        + dtUntill);
// Set Period for 1 Hour
values.put(CalendarContract.Events.DURATION, "+P1H");

values.put(CalendarContract.Events.HAS_ALARM, 1);

// Insert event to calendar
Uri uri = cr.insert(CalendarContract.Events.CONTENT_URI, values);
其中
dtuntil

SimpleDateFormat yyyyMMdd = new SimpleDateFormat("yyyyMMdd");
Calendar dt = Calendar.getInstance();

// Where untilDate is a date instance of your choice, for example 30/01/2012
dt.setTime(untilDate);

// If you want the event until 30/01/2012, you must add one day from our day because UNTIL in RRule sets events before the last day
dt.add(Calendar.DATE, 1);
String dtUntill = yyyyMMdd.format(dt.getTime());

Ref:

使用此代码,您可以通过编程方式将事件添加到设备日历中。我在棉花糖中测试过,它对我很好

private void addToDeviceCalendar(String startDate,String endDate, String title,String description, String location) {

        String stDate = startDate;
        String enDate = endDate;

        GregorianCalendar calDate = new GregorianCalendar();
        //GregorianCalendar calEndDate = new GregorianCalendar();

        SimpleDateFormat originalFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        SimpleDateFormat targetFormat = new SimpleDateFormat("yyyy,MM,dd,HH,mm");
        Date date,edate;
        try {
            date = originalFormat.parse(startDate);
            stDate=targetFormat.format(date);

        } catch (ParseException ex) {}

        long startMillis = 0;
        long endMillis = 0;
        String dates[] = stDate.split(",");

        SD_YeaR = dates[0];
        SD_MontH = dates[1];
        SD_DaY = dates[2];
        SD_HouR = dates[3];
        SD_MinutE = dates[4];


        /*Log.e("YeaR ", SD_YeaR);
        Log.e("MontH ",SD_MontH );
        Log.e("DaY ", SD_DaY);
        Log.e(" HouR", SD_HouR);
        Log.e("MinutE ", SD_MinutE);*/

        calDate.set(Integer.parseInt(SD_YeaR), Integer.parseInt(SD_MontH)-1, Integer.parseInt(SD_DaY), Integer.parseInt(SD_HouR), Integer.parseInt(SD_MinutE));
        startMillis = calDate.getTimeInMillis();
/*
        try {
            edate = originalFormat.parse(endDate);
            enDate=targetFormat.format(edate);

        } catch (ParseException ex) {}


        String end_dates[] = endDate.split(",");

        String ED_YeaR = end_dates[0];
        String ED_MontH = end_dates[1];
        String ED_DaY = end_dates[2];

        String ED_HouR = end_dates[3];
        String ED_MinutE = end_dates[4];


        calEndDate.set(Integer.parseInt(ED_YeaR), Integer.parseInt(ED_MontH)-1, Integer.parseInt(ED_DaY), Integer.parseInt(ED_HouR), Integer.parseInt(ED_MinutE));
        endMillis = calEndDate.getTimeInMillis();*/

        try {
            ContentResolver cr = getActivity().getContentResolver();
            ContentValues values = new ContentValues();
            values.put(CalendarContract.Events.DTSTART, startMillis);
            values.put(CalendarContract.Events.DTEND, calDate.getTimeInMillis() + 60 * 60 * 1000);
            values.put(CalendarContract.Events.TITLE, title);
            values.put(CalendarContract.Events.DESCRIPTION, description);
            values.put(CalendarContract.Events.EVENT_LOCATION,location);
            values.put(CalendarContract.Events.HAS_ALARM,1);
            values.put(CalendarContract.Events.CALENDAR_ID, 1);
            values.put(CalendarContract.Events.EVENT_TIMEZONE, Calendar.getInstance()
                    .getTimeZone().getID());
            System.out.println(Calendar.getInstance().getTimeZone().getID());
            if (ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.WRITE_CALENDAR) != PackageManager.PERMISSION_GRANTED) {

                return;
            }
            Uri uri = cr.insert(CalendarContract.Events.CONTENT_URI, values);

            long eventId = Long.parseLong(uri.getLastPathSegment());
            Log.d("Ketan_Event_Id", String.valueOf(eventId));

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

同意以上所有答案,但导入是日历Id。您不能使用1,因为三星手机的日历(S Planner)使用1。因此日历Id是您希望接收事件的电子邮件的Id。您可以按照特定事件的代码获取日历id

int calenderId=-1;
        String calenderEmaillAddress="xxx@gmail.com";
        String[] projection = new String[]{
                CalendarContract.Calendars._ID,
                CalendarContract.Calendars.ACCOUNT_NAME};
        ContentResolver cr = activity.getContentResolver();
        Cursor cursor = cr.query(Uri.parse("content://com.android.calendar/calendars"), projection,
                CalendarContract.Calendars.ACCOUNT_NAME + "=? and (" +
                        CalendarContract.Calendars.NAME + "=? or " +
                        CalendarContract.Calendars.CALENDAR_DISPLAY_NAME + "=?)",
                new String[]{calenderEmaillAddress, calenderEmaillAddress,
                        calenderEmaillAddress}, null);

        if (cursor.moveToFirst()) {

            if (cursor.getString(1).equals(calenderEmaillAddress))
                 calenderId=cursor.getInt(0); //youre calender id to be insered in above 2 answer


        }

以下是询问用户事件必须添加到哪个日历的方法。因为我的要求是这样的,没有在一个地方找到解决方案。我总结并提出了这个解决方案,希望它能帮助别人:)

final ContentResolver cr=this.getContentResolver();
光标;
if(Integer.parseInt(Build.VERSION.SDK)>=8)
cursor=cr.query(Uri.parse(“content://com.android.calendar/calendars),新字符串[]{“\u id”,“calendar\u displayName”},null,null,null);
其他的
cursor=cr.query(Uri.parse(“content://calendar/calendars),新字符串[]{“\u id”,“displayname”},null,null,null);
if(cursor!=null&&cursor.moveToFirst()){
最终字符串[]calNames=新字符串[cursor.getCount()];
final int[]calIds=new int[cursor.getCount()];
对于(int i=0;i=8)
newEvent=cr.insert(Uri.parse(“content://com.android.calendar/events",cv),;
其他的
newEvent=cr.insert(Uri.parse(“content://calendar/events",cv),;
if(newEvent!=null){
long id=long.parseLong(newEvent.getLastPathSegment());
ContentValues=新的ContentValues();
值。put(“事件id”,id);
价值。投入(“方法”,1);
value.put(“分钟”,15);//15分钟
if(Integer.parseInt(Build.VERSION.SDK)>=8)
cr.insert(Uri.parse(“content://com.android.calendar/reminders价值观);
其他的
cr.insert(Uri.parse(“content://calendar/reminders价值观);
}
dialog.cancel();
}
});
builder.create().show();
}
如果(光标!=null){
cursor.close();
}

别忘了添加清单权限

<uses-permission android:name="android.permission.READ_CALENDAR"/>
<uses-permission android:name="android.permission.WRITE_CALENDAR"/>

不,我想以编程方式添加此事件。在该链接中,它们也显示了上述方法。我所描述的内容怎么不符合程序?你的意思是你不想使用意图?您想在每个会话中以静默方式添加事件吗?是的,我想以静默方式将事件添加到默认日历。格式不应该是“yyyyMMdd”而不是“yyyyMMdd”吗?“m”表示根据以下内容的分钟数:报警仅以以下格式对我有效:
values.put(CalendarContract.Events.HAS\u报警,false)看看这个问题:cr.insert(CalendarContract.Events.CONTENT\uURI,values);在logcat中没有任何内容的情况下崩溃。PS:我已经根据Marshmallow添加并授予了权限。对于事件,CALENDAR_ID=1必须为2,对于生日事件,必须为3。。。感谢可能重复的@jww,他想安静地做,与其他问题不同。别忘了这句话@Ketan Ramani:不在Marshmellow设备上工作,但没有错误。这里的日历ID是什么意思???@Pradeepkumarredy我在上面声明它已经校准了。卡利德是
<uses-permission android:name="android.permission.READ_CALENDAR"/>
<uses-permission android:name="android.permission.WRITE_CALENDAR"/>
long calID = 3; // Make sure to which calender you want to add event 
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();


ContentResolver cr = getContentResolver();
ContentValues values = new ContentValues();
values.put(Events.DTSTART, startMillis);
values.put(Events.DTEND, endMillis);
values.put(Events.TITLE, "Hackathon");
values.put(Events.DESCRIPTION, "do some code");
values.put(Events.CALENDAR_ID, calID);
values.put(Events.EVENT_TIMEZONE, TimeZone.getDefault().getID());
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());