【问题标题】:How can I add event to the calendar automatically?如何自动将事件添加到日历?
【发布时间】:2013-04-10 16:33:46
【问题描述】:

如何自动将事件添加到日历中?如果我使用此源代码,它会打开包含已填充条目的日历,但我必须单击保存按钮来保存它。

public class CalendarApplicationActivity extends Activity
{  

public static final String[] EVENT_PROJECTION = new String[] 
{  
        Calendars._ID, // 0  
        Calendars.ACCOUNT_NAME, // 1  
        Calendars.CALENDAR_DISPLAY_NAME // 2  
};  


private static final int PROJECTION_DISPLAY_NAME_INDEX = 2;  

@Override 
public void onCreate(Bundle savedInstanceState)
{  
    super.onCreate(savedInstanceState);  
    setContentView(R.layout.activity_calendar_application);  
}  

public void onClick(View view) 
{  

    Intent intent = new Intent(Intent.ACTION_INSERT);  
    intent.setType("vnd.android.cursor.item/event");  
    intent.putExtra(Events.TITLE, "Learn Android");  
    intent.putExtra(Events.EVENT_LOCATION, "Home suit home");  
    intent.putExtra(Events.DESCRIPTION, "Download Examples");  

    GregorianCalendar calDate = new GregorianCalendar(2012, 10, 02);  
    intent.putExtra(CalendarContract.EXTRA_EVENT_BEGIN_TIME,  
            calDate.getTimeInMillis());  
    intent.putExtra(CalendarContract.EXTRA_EVENT_END_TIME,  
            calDate.getTimeInMillis());  

    intent.putExtra(CalendarContract.EXTRA_EVENT_ALL_DAY, true);  


    intent.putExtra(Events.ACCESS_LEVEL, Events.ACCESS_PRIVATE);  
    intent.putExtra(Events.AVAILABILITY, Events.AVAILABILITY_BUSY);  

    startActivity(intent);  

}  


}

【问题讨论】:

    标签: android android-intent android-emulator calendar android-calendar


    【解决方案1】:

    我向您发布了这段代码,该代码用于我在市场上的一个应用程序中。它会自动将事件添加到用户日历。它不使用需要用户操作的 Intent。

    public void addEvent(CalendarEvent evt) {
        //Log.d(Params.LOG_APP, "Insert event ["+evt+"]");
    
        try {
            Uri evtUri = ctx.getContentResolver().insert(getCalendarUri("events"), CalendarEvent.toContentValues(evt));
            Log.d(Params.LOG_APP, "" + evtUri);
        }
        catch(Throwable t) {
            //Log.e(Params.LOG_APP, "", t);
        }
    }
    
    public void setContext(Context context) {
        this.ctx = context;
        this.baseUri = getCalendarUriBase();
    }
    
    private Uri getCalendarUri(String path) {
        return Uri.parse(baseUri + "/" + path);
    }
    
    private String getCalendarUriBase() {
        String calendarUriBase = null;
        Uri calendars = Uri.parse("content://calendar/calendars");
        Cursor managedCursor = null;
        try {
            managedCursor = ctx.getContentResolver().query(calendars, null, null, null, null);
        } catch (Exception e) {
           // e.printStackTrace();
        }
    
        if (managedCursor != null) {
            calendarUriBase = "content://calendar/";
        } else {
            calendars = Uri.parse("content://com.android.calendar/calendars");
            try {
                managedCursor = ctx.getContentResolver().query(calendars, null, null, null, null);
            } catch (Exception e) {
               // e.printStackTrace();
            }
    
            if (managedCursor != null) {
                calendarUriBase = "content://com.android.calendar/";
            }
    
        }
    
        Log.d(Params.LOG_APP, "URI ["+calendarUriBase+"]");
        return calendarUriBase;
    }
    

    对于 ICS 及更高版本

    public void addEvent(CalendarEvent evt) {
    
        ContentResolver cr = context.getContentResolver();
        Uri uri = cr.insert(Events.CONTENT_URI, CalendarEvent.toICSContentValues(evt));
        System.out.println("Event URI ["+uri+"]");
    
    }
    

    CalendarEvent 就像

    public static ContentValues toContentValues(CalendarEvent evt) {
        ContentValues cv = new ContentValues();
        cv.put("calendar_id", evt.getIdCalendar());
        cv.put("title", evt.getTitle());
        cv.put("description", evt.getDescr());
        cv.put("eventLocation", evt.getLocation());
        cv.put("dtstart", evt.getStartTime());
        cv.put("dtend", evt.getEndTime());
        cv.put("eventStatus", 1);
        cv.put("visibility", 0);
        cv.put("transparency", 0);
    
        return cv;
    
    }
    
    public static ContentValues toICSContentValues(CalendarEvent evt) {
    
        ContentValues cv = new ContentValues();
        cv.put(Events.CALENDAR_ID, evt.getIdCalendar());
        cv.put(Events.TITLE, evt.getTitle());
        cv.put(Events.DESCRIPTION, evt.getDescr());
        cv.put(Events.EVENT_LOCATION, evt.getLocation());
        cv.put(Events.DTSTART, evt.getStartTime());
        cv.put(Events.DTEND, evt.getEndTime());
    
        Calendar cal = Calendar.getInstance();
        TimeZone tz = cal.getTimeZone();
    
        cv.put(Events.EVENT_TIMEZONE, tz.getDisplayName());
        /*
        cv.put(Events.STATUS, 1);
        cv.put(Events.VISIBLE, 0);
        cv.put("transparency", 0);
    
        return cv;
        */
    
        return cv;
    }
    

    【讨论】:

    • 我不完全了解 ICS,这是自动保存事件的一种方法吗?我对内容值有错误。我怎样才能像这样描述非静态值calendarevent.java
    • CalendarEvent 就像public class CalendarEvent { private String title; private String descr; private String location; private long startTime; private long endTime; private String idCalendar; // get and set methods 你有什么错误?
    • 我收到“04-19 15:09:51.645: E/ActivityThread(12428): Failed to find provider info for calendar”这个错误
    • 您应该在 getCalendarUriBase 中验证返回值。在我看来,您无法正确构建 URI,因为它显示“日历”。您是否调用 setContext 将上下文传递给方法?
    • @FrancescoAzzola 你用什么baseUri Url?是私人 val baseUri = "googleapis.com/calendar/v3"
    【解决方案2】:

    我使用以下代码在我自己创建的日历中添加事件

    public void SyncEvent(long id, int meeting_id, String EventName,
       String Stime, String Etime, String Description) {
    
     Calendar cal = Calendar.getInstance();
     cal.setTimeZone(TimeZone.getTimeZone("GMT-1"));
     Date dt = null;
     Date dt1 = null;
     try {
      dt = new SimpleDateFormat("yyyy-MM-dd HH:mm").parse(Stime);
      dt1 = new SimpleDateFormat("yyyy-MM-dd HH:mm").parse(Etime);
    
      Calendar beginTime = Calendar.getInstance();
      cal.setTime(dt);
    
      // beginTime.set(2013, 7, 25, 7, 30);
      beginTime.set(cal.get(Calendar.YEAR), cal.get(Calendar.MONTH),
      cal.get(Calendar.DATE), cal.get(Calendar.HOUR_OF_DAY),
      cal.get(Calendar.MINUTE));
    
      Calendar endTime = Calendar.getInstance();
      cal.setTime(dt1);
    
      // endTime.set(2013, 7, 25, 14, 30);
      // endTime.set(year, month, day, hourOfDay, minute);
      endTime.set(cal.get(Calendar.YEAR), cal.get(Calendar.MONTH),
      cal.get(Calendar.DATE), cal.get(Calendar.HOUR_OF_DAY),
      cal.get(Calendar.MINUTE));
    
      ContentResolver cr = this.mContext.getContentResolver();
      ContentValues values = new ContentValues();
    
      values.put(Events.DTSTART, beginTime.getTimeInMillis());
      values.put(Events.DTEND, endTime.getTimeInMillis());
      values.put(Events.TITLE, EventName);
      values.put(Events.DESCRIPTION, Description);
      values.put(Events.CALENDAR_ID, id);
      // values.put(Events._ID, meeting_id);
      values.put(Events.EVENT_TIMEZONE, TimeZone.getDefault().getID());
    
      Uri uri = cr.insert(Events.CONTENT_URI, values);
      long eventID = Long.parseLong(uri.getLastPathSegment());
     } catch (ParseException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
       }
    }
    

    【讨论】:

      【解决方案3】:

      如果您使用 Intent 与日历提供程序进行通信,那么,正如您所注意到的,日历应用会要求用户确认。这是因为使用 Intents 意味着您不需要请求任何特定权限。

      顺便说一句,Google 建议使用 Intents 与日历交互。

      但是,如果您确实想要自动插入事件,您的应用必须在清单中具有 WRITE_CALENDAR 权限。您不使用 Intent,而是使用 ContentResolver。您可以在 添加事件 部分的 https://developer.android.com/guide/topics/providers/calendar-provider.html 查看示例代码。

      【讨论】:

        【解决方案4】:

        此代码添加一个事件,并在日历视图中显示该事件。无需点击“保存”/用户交互。

                    long calID = 3;
                    long startMillis = 0;
                    long endMillis = 0;
                    Calendar beginTime = Calendar.getInstance();
                    beginTime.set(2015, 6, 12, 7, 30);// set(int year, int month, int day, int hourOfDay, int minute)
                    startMillis = beginTime.getTimeInMillis();
                    Calendar endTime = Calendar.getInstance();
                    endTime.set(2015, 6, 12, 8, 30);
                    endMillis = endTime.getTimeInMillis();
        
                    TimeZone tz = TimeZone.getDefault();
        
                    ContentResolver cr = getContentResolver();
                    ContentValues values = new ContentValues();
                    values.put(CalendarContract.Events.DTSTART, startMillis);
                    values.put(CalendarContract.Events.DTEND, endMillis);
                    values.put(CalendarContract.Events.TITLE, "Jazzercise");
                    values.put(CalendarContract.Events.DESCRIPTION, "Group workout");
                    values.put(CalendarContract.Events.CALENDAR_ID, calID);
                    values.put(CalendarContract.Events.EVENT_TIMEZONE,  tz.getID());
                    Uri uri = cr.insert(CalendarContract.Events.CONTENT_URI, values);
        
                    // get the event ID that is the last element in the Uri
                    long eventID = Long.parseLong(uri.getLastPathSegment());
        
        
                    Uri.Builder builder = CalendarContract.CONTENT_URI.buildUpon();
                    builder.appendPath("time");
                    ContentUris.appendId(builder, startMillis);
                    Intent intent = new Intent(Intent.ACTION_VIEW).setData(builder.build());
                    startActivity(intent);
        

        【讨论】:

        • 我在这一行遇到异常 Uri uri = cr.insert(CalendarContract.Events.CONTENT_URI, values);
        猜你喜欢
        • 2011-11-06
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多