如何找出日历意图的结果?

时间:2012-03-18 19:37:58

标签: android android-intent calendar google-calendar-api

从我的应用程序中,我正在启动日历:

    Calendar cal = Calendar.getInstance();              
    Intent intent = new Intent(Intent.ACTION_EDIT);
    intent.setType("vnd.android.cursor.item/event");
    intent.putExtra("beginTime", cal.getTimeInMillis());
    intent.putExtra("allDay", true);
    intent.putExtra("rrule", "FREQ=YEARLY");
    intent.putExtra("endTime", cal.getTimeInMillis()+60*60*1000);
    intent.putExtra("title", "Some title");
    startActivity(intent);

如果用户继续并保存此预先填充的日历条目,我无法弄清楚如何获取eventID。我还想知道用户是否取消了日历提示,并且没有保存这个新的预先填充的事件。

是否有任何相关内容返回onActivityResult(...),我可以将其用作日历事件的参考?我需要这个,所以我以后可以查找/打开日历事件进行查看/编辑。 [更新:]是的,尝试onActivityResult(...),并且在任何用户交互之前日历打开时,intent会立即返回,所以这没用。

我想通过使用意图(也让用户从设备上可用的各种日历中选择)切换到日历应用程序并避免从我的应用程序重新创建日历UE来实现此目的。我也想支持Android 2.2+。

6 个答案:

答案 0 :(得分:8)

这就是我的所作所为:

我在开始意图之前得到了下一个事件ID:

public static long getNewEventId(ContentResolver cr) {      
    Cursor cursor = cr.query(Events.CONTENT_URI, new String [] {"MAX(_id) as max_id"}, null, null, "_id");
    cursor.moveToFirst();
    long max_val = cursor.getLong(cursor.getColumnIndex("max_id"));     
    return max_val+1;
}

然后,我像往常一样调用意图:

        long event_id = EventUtility.getNewEventId(mContext.getContentResolver());

        Intent intent = new Intent(Intent.ACTION_INSERT)
        .setData(Events.CONTENT_URI)
        .putExtra(Events._ID, event_id)
        .putExtra(Events.TITLE, "title");

        startActivity(intent);

这就是技巧,在我的活动的onResume()中,我检查是否创建了与之前生成的event_id相同的新event_id。如果它们相同,则表示已创建新日历。然后,我将新数据存储在我的数据库中。

public static long getLastEventId(ContentResolver cr) {      
    Cursor cursor = cr.query(Events.CONTENT_URI, new String [] {"MAX(_id) as max_id"}, null, null, "_id");
    cursor.moveToFirst();
    long max_val = cursor.getLong(cursor.getColumnIndex("max_id"));     
    return max_val;
}

@Override
public void onResume() {
    super.onResume();

    long prev_id = EventUtility.getLastEventId(getContentResolver());

    // if prev_id == mEventId, means there is new events created
    // and we need to insert new events into local sqlite database.
    if (prev_id == mEventID) {
        // do database insert
    }
}

答案 1 :(得分:2)

我认为您可以在onResume方法中通过beginTime检查事件。肯定不会有2个具有相同beginTime的事件。

答案 2 :(得分:1)

也许您可以以编程方式插入事件并发送“编辑”它的意图。

答案 3 :(得分:0)

这可能听起来像是黑客..但是,您可以通过使用日历提供程序apis查询日历条目来检查OnCreate(当您的应用程序从日历应用程序到达前台时)是通过查询日历条目来保存还是取消已触发事件。

答案 4 :(得分:-1)

您可以拨打startActivity(intent)并覆盖startActivityForResult(intent, integer_constant)方法,而不是致电onActivityResult

https://developer.android.com/guide/components/activities/activity-lifecycle.html

答案 5 :(得分:-2)

听起来你想使用startActivityForResult而不是startActivity。它有一些文档here