简体   繁体   中英

Android : How to add future date event and reminder on device calendar?

I am able to set event and reminder in current date but when I am using future date time-stamp for setting future event on calendar it is not adding/showing any event on that future date. Here is my code for adding future date event :

 btnSetEvent.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            Date d1 = new Date(1472570400);//Tue, 30 Aug 2016 15:20:00 GMT
            Calendar cal1 = Calendar.getInstance();
            cal1.setTime(d1);

            Date d2 = new Date(1472574000);//Tue, 30 Aug 2016 16:20:00 GMT
            Calendar cal2 = Calendar.getInstance();
            cal2.setTime(d2);

            Uri EVENTS_URI = Uri.parse("content://com.android.calendar/events");
            ContentResolver cr = getContentResolver();

            // event insert
            ContentValues values = new ContentValues();
            values.put("calendar_id", 1);
            values.put("title", "Reminder Title");
            values.put("allDay", 0);
            values.put(CalendarContract.Events.EVENT_TIMEZONE, TimeZone.getDefault().getID());                

            values.put("dtstart", cal1.getTimeInMillis() ); // event starts at Tue, 30 Aug 2016 15:20:00
            values.put("dtend", cal2.getTimeInMillis()); // ends at Tue, 30 Aug 2016 16:20:00 GMT

            System.out.println("ALARM TIMES START : " + cal1.getTimeInMillis());
            System.out.println("ALARM TIMES END : "+cal2.getTimeInMillis());

            values.put("description", "Reminder description");                
            values.put("hasAlarm", 1);
            Uri event = cr.insert(EVENTS_URI, values);

            // reminder insert                
            Uri REMINDERS_URI = Uri.parse("content://com.android.calendar/reminders");
            values = new ContentValues();
            values.put( "event_id", Long.parseLong(event.getLastPathSegment()));               

            values.put( "method", 1);
            values.put( "minutes", 1); //Notify before the exact time
            cr.insert( REMINDERS_URI, values );
        }
    });
}

Thanks in advance.

This is because your long input dates are wrong. I debug them and they show 16 Jan 1970, not 30 Aug 2016.

You don't need to use Date class. Simply call:

Calendar cal1 = new GregorianCalendar(2016, Calendar.AUGUST, 30, 15, 20);
Calendar cal2 = new GregorianCalendar(2016, Calendar.AUGUST, 30, 16, 20);

Also if you have a long value, you can call cal1.setTimeInMillis(millis) .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM