2016-08-02 62 views
1

我可以在當前日期中設置事件和提醒,但是當我使用未來日期時間戳在日曆上設置未來事件時,它不會在該未來日期添加/顯示任何事件。這裏是我添加未來日期事件的代碼:Android:如何在設備日曆上添加未來的日期事件和提醒?

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

在此先感謝。

回答

2

這是因爲您的長輸入日期錯誤。我調試他們,他們顯示1970年1月16日,而不是2016年8月30日。

您不需要使用Date類。只需致電:

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

此外,如果您有很長的價值,您可以致電cal1.setTimeInMillis(millis)

+0

謝謝我修復我的時間戳長值和** cal1.setTimeInMillis(millis)**爲我工作。 – Harry