简体   繁体   中英

How to add a calendar event using Intents?

I'm trying to insert a calendar event for 2.2 and 2.3 devices. I'm using the intents approach, as described here:

http://developer.android.com/guide/topics/providers/calendar-provider.html#intents

It worked on a 4.1 device.

But I need it compatible with 2.2+ devices, so I've refactored the app to get rid of CalendarContract.CONTENT_URI so that it can run in versions < 14.

I'm now using this Uri, which AFAIK is compatible since Froyo:

    content://com.android.calendar

But I'm always having this exception in Froyo and Gingerbread devices:

    android.content.ActivityNotFoundException: No Activity found to handle Intent { act=android.intent.action.INSERT dat=content://com.android.calendar/events (has extras) }

These intents also fail:

    Intent { act=android.intent.action.VIEW dat=content://com.android.calendar/time/1386926751452 }

    Intent { act=android.intent.action.INSERT dat=content://com.android.calendar/events (has extras) }

    Intent { act=android.intent.action.EDIT dat=content://com.android.calendar/events (has extras) }

I've nonetheless tried the previous content Uri (content://calendar), even knowing it was for 1.5 and 1.6 with identical result.

No need to say I've checked the calendar is installed in every device I used for testing.

Am I missing something?

I found the solution in this answer .

The content provider Uri only works for API 14 onwards. For previous OS versions, the intent should not have the data uri set, instead the calendar app MIME type is required:

    Intent intent = new Intent(Intent.ACTION_EDIT);
    if (Build.VERSION.SDK_INT >= 14) {
        intent.setData("content://com.android.calendar/events");
    } else {
        intent.setType("vnd.android.cursor.item/event");
    }

Surprisingly, the intent for just opening the calendar works with the content provider Uri (without the "events" path). Turns out that this code works from Froyo to newer ICS devices:

    Uri.Builder builder = Uri.parse("content://com.android.calendar").buildUpon();
    builder.appendPath("time");
    ContentUris.appendId(builder, System.currentTimeMillis());
    Intent intent = new Intent(Intent.ACTION_VIEW).setData(builder.build());

    startActivity(intent);

I think it's time for guys at Google to roll out some kind of compatibility library for the Calendar. Would be really nice to be able to launch intents (and even accessing the ContentProvider) without caring which OS version we are working with. Yes I know the MIME type is not official and the database has changed, and therefore it might not work in some devices. But SOME support for older devices is better than NO support at all.

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