简体   繁体   中英

Android Calendar Intent Code Explanation

I wanted to open up the android native calendar application on a button click in my application. I have searched online and I have found the code below:

Intent intent = new Intent(Intent.ACTION_EDIT);  
intent.setType("vnd.android.cursor.item/event");
intent.putExtra("title", "Some title");
intent.putExtra("description", "Some description");
intent.putExtra("beginTime", eventStartInMillis);
intent.putExtra("endTime", eventEndInMillis);

startActivity(intent);

Could someone please explain this code to me?

To answer the question about what the code does

Intent intent = new Intent(Intent.ACTION_EDIT);  

Creates a new Intent corresponding with the Intent Action ACTION_EDIT . This is a generic Intent Action, meaning that just this isn't enough to launch the right Activity automatically. This is why the next thing we do is set the MIME type of the Intent . Since we want to launch the Calendar editor, we set the type to vnd.android.cursor.item/event :

intent.setType("vnd.android.cursor.item/event");

This corresponds with the manifest entry. Notice the data node (Jellybean version manifest shown).

<intent-filter>
    <action android:name="android.intent.action.EDIT" />
    <action android:name="android.intent.action.INSERT" />
    <category android:name="android.intent.category.DEFAULT" />
    <!-- mime type -->
    <data android:mimeType="vnd.android.cursor.item/event" /> 
</intent-filter>

The putExtra() calls allow you to specify event characteristics such as title of the event, start and end time, etc.

Then we start the Activity. The result is something like this:

在此处输入图片说明

And there you go, you have opened the Android calendar app to add an event!

Warning: Mileage may vary

But what if you don't want to call on the event editor? If all you want is to open up the Android calendar app, you can use PackageManager#getLaunchIntentForPackage() (provided that: the package name doesn't change, the Android calendar is installed, and that you can get a reference to the PackageManager ).

Example from an Activity (using MainActivity.this to highlight the fact that I'm launching from an Activity):

Intent i = MainActivity.this.getPackageManager().getLaunchIntentForPackage("com.android.calendar");
if (i != null)
  startActivity(i);

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