From df75bdcc5546112958a6a5834c1a7e060f88bc68 Mon Sep 17 00:00:00 2001 From: Scott Main Date: Tue, 15 Jan 2013 15:12:13 -0800 Subject: rewrite intent guide and add doc with intents supported by platform apps Change-Id: Ida7ccbc693e7635198fd368b9560b7843266c7cc --- docs/html/guide/components/intents-common.jd | 1312 ++++++++++++++++ docs/html/guide/components/intents-filters.jd | 1640 +++++++++----------- docs/html/guide/components/services.jd | 54 +- docs/html/guide/guide_toc.cs | 13 +- .../html/guide/topics/manifest/category-element.jd | 8 + docs/html/guide/topics/manifest/data-element.jd | 147 +- docs/html/images/components/intent-filters@2x.png | Bin 0 -> 43968 bytes docs/html/training/basics/intents/filters.jd | 4 +- docs/html/training/basics/intents/sending.jd | 8 +- docs/html/training/sharing/send.jd | 14 +- 10 files changed, 2195 insertions(+), 1005 deletions(-) create mode 100644 docs/html/guide/components/intents-common.jd create mode 100644 docs/html/images/components/intent-filters@2x.png (limited to 'docs/html') diff --git a/docs/html/guide/components/intents-common.jd b/docs/html/guide/components/intents-common.jd new file mode 100644 index 0000000..f09ef9f --- /dev/null +++ b/docs/html/guide/components/intents-common.jd @@ -0,0 +1,1312 @@ +page.title=Common Intents +page.tags="IntentFilter" +@jd:body + +
+ +
+ + +

An intent allows you to start an activity in another app by describing a simple +action you'd like to perform (such as "view a map" or "take a picture") +in an {@link android.content.Intent} object. This type of intent is +called an implicit intent because it does not specify the app component +to start, but instead specifies an action and provides some +data with which to perform the action.

+ +

When you call +{@link android.content.Context#startActivity startActivity()} or +{@link android.app.Activity#startActivityForResult startActivityForResult()} and pass it an +implicit intent, the system resolves the intent to an app that can handle the intent +and starts its corresponding {@link android.app.Activity}. If there's more than one app +that can handle the intent, the system presents the user with a dialog to pick which app +to use.

+ +

This page describes several implicit intents that you can use to perform common actions, +organized by the type of app that handles the intent. Each section also shows how you can +create an intent filter to +advertise your app's ability to perform the same action.

+ +

Caution: If there are no apps on the device that can receive +the implicit intent, your app will crash when it calls {@link android.content.Context#startActivity +startActivity()}. To first verify that an app exists to receive the intent, call {@link +android.content.Intent#resolveActivity resolveActivity()} on your {@link android.content.Intent} +object. If the result is non-null, there is at least one app that can handle the intent and +it's safe to call {@link android.content.Context#startActivity startActivity()}. If the result is +null, you should not use the intent and, if possible, you should disable the feature that invokes +the intent.

+ + +

If you're not familiar with how to create intents or intent filters, you should first read +Intents and Intent Filters.

+ + + + + +

Camera

+ + + +

Capture a picture or video and return it

+ +

To open a camera app and receive the resulting photo or video, use the {@link +android.provider.MediaStore#ACTION_IMAGE_CAPTURE} or {@link +android.provider.MediaStore#ACTION_VIDEO_CAPTURE} action. Also specify the URI location where you'd +like the camera to save the photo or video, in the {@link android.provider.MediaStore#EXTRA_OUTPUT} +extra.

+ + +
+
Action
+
{@link android.provider.MediaStore#ACTION_IMAGE_CAPTURE} or
+ {@link android.provider.MediaStore#ACTION_VIDEO_CAPTURE}
+ +
Data URI Scheme
+
None
+ +
MIME Type
+
None
+ +
Extras
+
+
+
{@link android.provider.MediaStore#EXTRA_OUTPUT}
+
The URI location where the camera app should save the photo or + video file (as a {@link android.net.Uri} object).
+
+
+
+ +

When the camera app successfully returns +focus to your activity (your app receives the {@link android.app.Activity#onActivityResult +onActivityResult()} callback), you can access the photo or video at the URI you specified +with the {@link android.provider.MediaStore#EXTRA_OUTPUT} value.

+ +

Note: When you use {@link +android.provider.MediaStore#ACTION_IMAGE_CAPTURE} to capture a photo, the camera may also return a +downscaled copy (a thumbnail) of the photo in the result {@link +android.content.Intent}, saved as a {@link android.graphics.Bitmap} in an extra field named +"data".

+ + +

Example intent:

+
+static final int REQUEST_IMAGE_CAPTURE = 1;
+static final Uri mLocationForPhotos;
+
+public void capturePhoto(String targetFilename) {
+    Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
+    intent.putExtra(MediaStore.EXTRA_OUTPUT,
+            Uri.withAppendedPath(mLocationForPhotos, targetFilename);
+    if (intent.resolveActivity(getPackageManager()) != null) {
+        startActivityForResult(intent, REQUEST_IMAGE_CAPTURE);
+    }
+}
+
+@Override
+protected void onActivityResult(int requestCode, int resultCode, Intent data) {
+    if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
+        Bitmap thumbnail = data.getParcelable("data");
+        // Do other work with full size photo saved in mLocationForPhotos
+        ...
+    }
+}
+
+ +

For more information about how to use this intent to capture a photo, including +how to create an appropriate {@link android.net.Uri} for the output location, read +Taking Photos Simply or +Taking Videos Simply.

+ +

Example intent filter:

+
+<activity ...>
+    <intent-filter>
+        <action android:name="android.media.action.IMAGE_CAPTURE" />
+        <category android:name="android.intent.category.DEFAULT" />
+    </intent-filter>
+</activity>
+
+ +

When handling this intent, your activity should check for the {@link +android.provider.MediaStore#EXTRA_OUTPUT} extra in the incoming {@link android.content.Intent}, +then save the captured image or video at the location specified by that extra and call {@link +android.app.Activity#setResult(int,Intent) setResult()} with an +{@link android.content.Intent} that includes a compressed thumbnail +in an extra named "data".

+ + + + +

Contacts/People App

+ + +

Select a contact

+ +

To have the user select a contact and provide your app access to all the contact information, +use the {@link android.content.Intent#ACTION_PICK} action and specify the MIME type to +{@link android.provider.ContactsContract.Contacts#CONTENT_TYPE +Contacts.CONTENT_TYPE}.

+ +

The result {@link android.content.Intent} delivered to your {@link +android.app.Activity#onActivityResult onActivityResult()} callback contains the +content: URI pointing to the selected contact. The response grants +your app temporary permissions to read that contact using the Contacts Provider API even if +your app does not include the {@link android.Manifest.permission#READ_CONTACTS} permission.

+ +

Tip: If you need access to only a specific piece of contact +information, such as a phone number or email address, instead see the next section about how to +select specific contact data.

+ +
+
Action
+
{@link android.content.Intent#ACTION_PICK}
+ +
Data URI Scheme
+
None
+ +
MIME Type
+
{@link android.provider.ContactsContract.Contacts#CONTENT_TYPE +Contacts.CONTENT_TYPE} +
+
+ +

Example intent:

+
+static final int REQUEST_SELECT_CONTACT = 1;
+
+public void selectContact() {
+    Intent intent = new Intent(Intent.ACTION_PICK);
+    intent.setType(ContactsContract.Contacts.CONTENT_TYPE);
+    if (intent.resolveActivity(getPackageManager()) != null) {
+        startActivityForResult(intent, REQUEST_SELECT_CONTACT);
+    }
+}
+
+@Override
+protected void onActivityResult(int requestCode, int resultCode, Intent data) {
+    if (requestCode == REQUEST_SELECT_CONTACT && resultCode == RESULT_OK) {
+        Uri contactUri = data.getData();
+        // Do something with the selected contact at contactUri
+        ...
+    }
+}
+
+ +

For information about how to retrieve contact details once you have the contact URI, +read Retrieving Details +for a Contact. Remember, when you retrieve the contact URI with the above intent, you +do not need the {@link android.Manifest.permission#READ_CONTACTS} permission +to read details for that contact.

+ + + + +

Select specific contact data

+ +

To have the user select a specific piece of information from a contact, such as +a phone number, email address, or other data type, use the +{@link android.content.Intent#ACTION_PICK} action and specify the MIME type to one +of the content types listed below, such as +{@link android.provider.ContactsContract.CommonDataKinds.Phone#CONTENT_TYPE +CommonDataKinds.Phone.CONTENT_TYPE} to get the contact's phone number.

+ +

If you need to retrieve only one type of data from a contact, this technique with a +{@code CONTENT_TYPE} from the +{@link android.provider.ContactsContract.CommonDataKinds} classes is more efficient than +using the {@link android.provider.ContactsContract.Contacts#CONTENT_TYPE +Contacts.CONTENT_TYPE} (as shown in the previous section) because the result provides you direct +access to the desired data without requiring you to perform a more complex query to Contacts Provider.

+ +

The result {@link android.content.Intent} delivered to your {@link +android.app.Activity#onActivityResult onActivityResult()} callback contains the +content: URI pointing to the selected contact data. The response grants +your app temporary permissions to read that contact data even if your app does +not include the {@link android.Manifest.permission#READ_CONTACTS} permission.

+ +
+
Action
+
{@link android.content.Intent#ACTION_PICK}
+ +
Data URI Scheme
+
None
+ +
MIME Type
+
+
+
{@link android.provider.ContactsContract.CommonDataKinds.Phone#CONTENT_TYPE +CommonDataKinds.Phone.CONTENT_TYPE}
+
Pick from contacts with a phone number.
+
{@link android.provider.ContactsContract.CommonDataKinds.Email#CONTENT_TYPE +CommonDataKinds.Email.CONTENT_TYPE}
+
Pick from contacts with an email address.
+
{@link android.provider.ContactsContract.CommonDataKinds.StructuredPostal#CONTENT_TYPE +CommonDataKinds.StructuredPostal.CONTENT_TYPE}
+
Pick from contacts with a postal address.
+
+

Or one of many other {@code CONTENT_TYPE} values + under {@link android.provider.ContactsContract}.

+
+
+ +

Example intent:

+
+static final int REQUEST_SELECT_PHONE_NUMBER = 1;
+
+public void selectContact() {
+    // Start an activity for the user to pick a phone number from contacts
+    Intent intent = new Intent(Intent.ACTION_PICK);
+    intent.setType(CommonDataKinds.Phone.CONTENT_TYPE);
+    if (intent.resolveActivity(getPackageManager()) != null) {
+        startActivityForResult(intent, REQUEST_SELECT_PHONE_NUMBER);
+    }
+}
+
+@Override
+protected void onActivityResult(int requestCode, int resultCode, Intent data) {
+    if (requestCode == REQUEST_SELECT_PHONE_NUMBER && resultCode == RESULT_OK) {
+        // Get the URI and query the content provider for the phone number
+        Uri contactUri = data.getData();
+        String[] projection = new String[]{CommonDataKinds.Phone.NUMBER};
+        Cursor cursor = getContentResolver().query(contactUri, projection,
+                null, null, null);
+        // If the cursor returned is valid, get the phone number
+        if (cursor != null && cursor.moveToFirst()) {
+            int numberIndex = cursor.getColumnIndex(CommonDataKinds.Phone.NUMBER);
+            String number = cursor.getString(numberIndex);
+            // Do something with the phone number
+            ...
+        }
+    }
+}
+
+ + + + + +

View a contact

+ +

To display the details for a known contact, use the {@link android.content.Intent#ACTION_VIEW} +action and specify the contact with a {@code content:} URI as the intent data.

+ +

There are primarily two ways to initially retrieve the contact's URI:

+ + +
+
Action
+
{@link android.content.Intent#ACTION_VIEW}
+ +
Data URI Scheme
+
{@code content:<URI>}
+ +
MIME Type
+
None. The type is inferred from contact URI. +
+
+ +

Example intent:

+
+public void viewContact(Uri contactUri) {
+    Intent intent = new Intent(Intent.ACTION_VIEW, contactUri);
+    if (intent.resolveActivity(getPackageManager()) != null) {
+        startActivity(intent);
+    }
+}
+
+ + + +

Edit an existing contact

+ +

To edit a known contact, use the {@link android.content.Intent#ACTION_EDIT} +action, specify the contact with a {@code content:} URI +as the intent data, and include any known contact information in extras specified by +constants in {@link android.provider.ContactsContract.Intents.Insert}.

+ +

There are primarily two ways to initially retrieve the contact URI:

+ + +
+
Action
+
{@link android.content.Intent#ACTION_EDIT}
+ +
Data URI Scheme
+
{@code content:<URI>}
+ +
MIME Type
+
The type is inferred from contact URI. +
+ +
Extras (optional)
+
One or more of the extras defined in {@link android.provider.ContactsContract.Intents.Insert} +so you can populate fields of the contact details. +
+
+ +

Example intent:

+
+public void editContact(Uri contactUri, String email) {
+    Intent intent = new Intent(Intent.ACTION_EDIT);
+    intent.setDataAndType(contactUri, Contacts.CONTENT_TYPE);
+    intent.putExtra(Intents.Insert.EMAIL, email);
+    if (intent.resolveActivity(getPackageManager()) != null) {
+        startActivity(intent);
+    }
+}
+
+ +

For more information about how to edit a contact, read Modifying +Contacts Using Intents.

+ + + + +

Insert a contact

+ +

To insert a new contact, use the {@link android.content.Intent#ACTION_INSERT} action, +specify {@link android.provider.ContactsContract.Contacts#CONTENT_TYPE Contacts.CONTENT_TYPE} as +the MIME type, and include any known contact information in extras specified by +constants in {@link android.provider.ContactsContract.Intents.Insert}. + +

+
Action
+
{@link android.content.Intent#ACTION_INSERT}
+ +
Data URI Scheme
+
None
+ +
MIME Type
+
{@link android.provider.ContactsContract.Contacts#CONTENT_TYPE Contacts.CONTENT_TYPE}
+ +
Extras (optional)
+
One or more of the extras defined in {@link android.provider.ContactsContract.Intents.Insert}. +
+
+ +

Example intent:

+
+public void insertContact(String name, String email) {
+    Intent intent = new Intent(Intent.ACTION_INSERT);
+    intent.setType(Contacts.CONTENT_TYPE);
+    intent.putExtra(Intents.Insert.NAME, name);
+    intent.putExtra(Intents.Insert.EMAIL, email);
+    if (intent.resolveActivity(getPackageManager()) != null) {
+        startActivity(intent);
+    }
+}
+
+ +

For more information about how to insert a contact, read Modifying +Contacts Using Intents.

+ + + + + + + +

Email

+ + +

Compose an email with optional attachments

+ + +

To compose an email, use one of the below actions based on whether you'll include attachments, +and include email details such as the recipient and subject using the extra keys listed below.

+ +
+
Action
+
{@link android.content.Intent#ACTION_SENDTO} (for no attachment) or
+ {@link android.content.Intent#ACTION_SEND} (for one attachment) or
+ {@link android.content.Intent#ACTION_SEND_MULTIPLE} (for multiple attachments)
+ +
Data URI Scheme
+
None
+ +
MIME Type
+
+
+
{@link org.apache.http.protocol.HTTP#PLAIN_TEXT_TYPE} ("text/plain") +
"*/*" +
+
+ +
Extras (optional)
+
+
+
{@link android.content.Intent#EXTRA_EMAIL Intent.EXTRA_EMAIL}
+
A string array of all "To" recipient email addresses.
+
{@link android.content.Intent#EXTRA_CC Intent.EXTRA_CC}
+
A string array of all "CC" recipient email addresses.
+
{@link android.content.Intent#EXTRA_BCC Intent.EXTRA_BCC}
+
A string array of all "BCC" recipient email addresses.
+
{@link android.content.Intent#EXTRA_SUBJECT Intent.EXTRA_SUBJECT}
+
A string with the email subject.
+
{@link android.content.Intent#EXTRA_TEXT Intent.EXTRA_TEXT}
+
A string with the body of the email.
+
{@link android.content.Intent#EXTRA_STREAM Intent.EXTRA_STREAM}
+
A {@link android.net.Uri} pointing to the attachment. If using the + {@link android.content.Intent#ACTION_SEND_MULTIPLE} action, this should instead + be an {@link java.util.ArrayList} containing multiple {@link android.net.Uri} objects.
+
+
+ +
+ + +

Example intent:

+
+public void composeEmail(String[] addresses, String subject, Uri attachment) {
+    Intent intent = new Intent(Intent.ACTION_SEND);
+    intent.setType("*/*");
+    intent.putExtra(Intent.EXTRA_EMAIL, addresses);
+    intent.putExtra(Intent.EXTRA_SUBJECT, subject);
+    intent.putExtra(Intent.EXTRA_STREAM, attachment);
+    if (intent.resolveActivity(getPackageManager()) != null) {
+        startActivity(intent);
+    }
+}
+
+ +

If you want to ensure that your intent is handled only by an email app (and not other +text messaging or social apps), then use the {@link android.content.Intent#ACTION_SENDTO} action +and include the {@code "mailto:"} data scheme. For example:

+ +
+public void composeEmail(String[] addresses, String subject) {
+    Intent intent = new Intent(Intent.ACTION_SENDTO);
+    intent.setData(Uri.parse("mailto:")); // only email apps should handle this
+    intent.putExtra(Intent.EXTRA_EMAIL, addresses);
+    intent.putExtra(Intent.EXTRA_SUBJECT, subject);
+    if (intent.resolveActivity(getPackageManager()) != null) {
+        startActivity(intent);
+    }
+}
+
+ + +

Example intent filter:

+
+<activity ...>
+    <intent-filter>
+        <action android:name="android.intent.action.SEND" />
+        <data android:type="*/*" />
+        <category android:name="android.intent.category.DEFAULT" />
+    </intent-filter>
+    <intent-filter>
+        <action android:name="android.intent.action.SENDTO" />
+        <data android:scheme="mailto" />
+        <category android:name="android.intent.category.DEFAULT" />
+    </intent-filter>
+</activity>
+
+ + + + + + + + + + + + + + + + +

File Storage

+ + + +

Retrieve a specific type of file

+ +

To request that the user select a file such as a document or photo and return a reference to +your app, use the {@link android.content.Intent#ACTION_GET_CONTENT} action and specify your desired +MIME type. The file reference returned to your app is transient to your activity's current +lifecycle, so if you want to access it later you must import a copy that you can read later. +This intent also allows the user to create a new file in the process (for +example, instead of selecting an existing photo, the user can capture a new photo with the camera). +

+ +

The result intent delivered to your {@link android.app.Activity#onActivityResult +onActivityResult()} method includes data with a URI pointing to the file. +The URI could be anything, such as an {@code http:} URI, {@code file:} URI, or {@code content:} +URI. However, if you'd like to restrict selectable files to only those that are accessible +from a content provider (a {@code content:} URI) and that are available as a file stream with {@link +android.content.ContentResolver#openFileDescriptor openFileDescriptor()}, you should add +the {@link android.content.Intent#CATEGORY_OPENABLE} category to your intent.

+ +

On Android 4.3 (API level 18) and higher, +you can also allow the user to select multiple files by adding +{@link android.content.Intent#EXTRA_ALLOW_MULTIPLE} to the intent, set to {@code true}. +You can then access each of the selected files in a {@link android.content.ClipData} +object returned by {@link android.content.Intent#getClipData()}.

+ + +
+
Action
+
{@link android.content.Intent#ACTION_GET_CONTENT}
+ +
Data URI Scheme
+
None
+ +
MIME Type
+
The MIME type corresponding to the file type the user should select. +
+ +
Extras (optional)
+
+
+
{@link android.content.Intent#EXTRA_ALLOW_MULTIPLE} +
A boolean declaring whether the user can select more than one file at a time. +
+
{@link android.content.Intent#EXTRA_LOCAL_ONLY} +
A boolean that declares whether the returned file must be available directly from + the device, rather than requiring a download from a remote service. +
+
+
+ +
Category (optional)
+
+
+
{@link android.content.Intent#CATEGORY_OPENABLE}
+
To return only "openable" files that can be represented as a file stream + with {@link android.content.ContentResolver#openFileDescriptor openFileDescriptor()}.
+
+
+ +
+ +

Example intent to get a photo:

+
+static final int REQUEST_IMAGE_GET = 1;
+
+public void selectImage() {
+    Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
+    intent.setType("image/*");
+    if (intent.resolveActivity(getPackageManager()) != null) {
+        startActivityForResult(intent, REQUEST_IMAGE_GET);
+    }
+}
+
+@Override
+protected void onActivityResult(int requestCode, int resultCode, Intent data) {
+    if (requestCode == REQUEST_IMAGE_GET && resultCode == RESULT_OK) {
+        Bitmap thumbnail = data.getParcelable("data");
+        Uri fullPhotoUri = data.getData();
+        // Do work with photo saved at fullPhotoUri
+        ...
+    }
+}
+
+ +

Example intent filter to return a photo:

+
+<activity ...>
+    <intent-filter>
+        <action android:name="android.intent.action.GET_CONTENT" />
+        <data android:type="image/*" />
+        <category android:name="android.intent.category.DEFAULT" />
+        <!-- The OPENABLE category declares that the returned file is accessible
+             from a content provider that supports {@link android.provider.OpenableColumns}
+             and {@link android.content.ContentResolver#openFileDescriptor ContentResolver.openFileDescriptor()} -->
+        <category android:name="android.intent.category.OPENABLE" />
+    </intent-filter>
+</activity>
+
+ + + + + + +

Open a specific type of file

+ +

Instead of retrieving a copy of a file that you must import to your app +(by using the {@link android.content.Intent#ACTION_GET_CONTENT} action), when running on Android +4.4 or higher, you can instead request to open a file that's managed by another app by +using the {@link android.content.Intent#ACTION_OPEN_DOCUMENT} action and specifying a MIME type. +To also allow the user to instead create a new document that your app can write to, use the {@link +android.content.Intent#ACTION_CREATE_DOCUMENT} action instead. For example, instead of +selecting from existing PDF documents, the {@link android.content.Intent#ACTION_CREATE_DOCUMENT} +intent allows users to select where they'd like to create a new document (within another app +that manages the document's storage)—your app then receives the URI location of where it +can write the new document.

+ +

Whereas the intent delivered to your {@link android.app.Activity#onActivityResult +onActivityResult()} method from the {@link android.content.Intent#ACTION_GET_CONTENT} action may +return a URI of any type, the result intent from {@link android.content.Intent#ACTION_OPEN_DOCUMENT} +and {@link android.content.Intent#ACTION_CREATE_DOCUMENT} always specify the chosen file as a {@code +content:} URI that's backed by a {@link android.provider.DocumentsProvider}. You can open the +file with {@link android.content.ContentResolver#openFileDescriptor openFileDescriptor()} and +query its details using columns from {@link android.provider.DocumentsContract.Document}.

+ +

The returned URI grants your app long-term read access to the file (also possibly +with write access). So the {@link android.content.Intent#ACTION_OPEN_DOCUMENT} action is +particularly useful (instead of using {@link android.content.Intent#ACTION_GET_CONTENT}) +when you want to read an existing file without making a copy into your app, +or when you want to open and edit a file in place.

+ +

You can also allow the user to select multiple files by adding +{@link android.content.Intent#EXTRA_ALLOW_MULTIPLE} to the intent, set to {@code true}. +If the user selects just one item, then you can retrieve the item from {@link +android.content.Intent#getData()}. If the user selects more than one item, then {@link +android.content.Intent#getData()} returns null and you must instead +retrieve each item from a {@link android.content.ClipData} +object that is returned by {@link android.content.Intent#getClipData()}.

+ +

Note: Your intent must specify a MIME type and +must declare the {@link android.content.Intent#CATEGORY_OPENABLE} category. If +appropriate, you can specify more than one MIME type by adding an array of MIME types with the +{@link android.content.Intent#EXTRA_MIME_TYPES} extra—if you do so, you must set the +primary MIME type in {@link android.content.Intent#setType setType()} to {@code "*/*"}.

+ +
+
Action
+
{@link android.content.Intent#ACTION_OPEN_DOCUMENT} or
+{@link android.content.Intent#ACTION_CREATE_DOCUMENT}
+ +
Data URI Scheme
+
None
+ +
MIME Type
+
The MIME type corresponding to the file type the user should select. +
+ +
Extras (optional)
+
+
+
{@link android.content.Intent#EXTRA_MIME_TYPES} +
An array of MIME types corresponding to the types of files your app is + requesting. When you use this extra, you must set the primary MIME type in + {@link android.content.Intent#setType setType()} to {@code "*/*"}.
+
{@link android.content.Intent#EXTRA_ALLOW_MULTIPLE} +
A boolean that declares whether the user can select more than one file at a time. +
+
{@link android.content.Intent#EXTRA_TITLE} +
For use with {@link android.content.Intent#ACTION_CREATE_DOCUMENT} to specify + an initial file name. +
+
{@link android.content.Intent#EXTRA_LOCAL_ONLY} +
A boolean that declares whether the returned file must be available directly from + the device, rather than requiring a download from a remote service. +
+
+
+ +
Category
+
+
+
{@link android.content.Intent#CATEGORY_OPENABLE}
+
To return only "openable" files that can be represented as a file stream + with {@link android.content.ContentResolver#openFileDescriptor openFileDescriptor()}.
+
+
+ +
+ +

Example intent to get a photo:

+
+static final int REQUEST_IMAGE_OPEN = 1;
+
+public void selectImage() {
+    Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
+    intent.setType("image/*");
+    intent.addCategory(Intent.CATEGORY_OPENABLE);
+    // Only the system receives the ACTION_OPEN_DOCUMENT, so no need to test.
+    startActivityForResult(intent, REQUEST_IMAGE_OPEN);
+}
+
+@Override
+protected void onActivityResult(int requestCode, int resultCode, Intent data) {
+    if (requestCode == REQUEST_IMAGE_OPEN && resultCode == RESULT_OK) {
+        Uri fullPhotoUri = data.getData();
+        // Do work with full size photo saved at fullPhotoUri
+        ...
+    }
+}
+
+ +

Third party apps cannot actually respond to an intent with the +{@link android.content.Intent#ACTION_OPEN_DOCUMENT} action. Instead, the system receives this +intent and displays all the files available from various apps in a unified user interface.

+ +

To provide your app's files in this UI and allow other apps to open them, you must implement +a {@link android.provider.DocumentsProvider} and include an intent filter for +{@link android.provider.DocumentsContract#PROVIDER_INTERFACE} +({@code "android.content.action.DOCUMENTS_PROVIDER"}). For example: + +

+<provider ...
+    android:grantUriPermissions="true"
+    android:exported="true"
+    android:permission="android.permission.MANAGE_DOCUMENTS">
+    <intent-filter>
+        <action android:name="android.content.action.DOCUMENTS_PROVIDER" />
+    </intent-filter>
+</provider>
+
+ +

For more information about how to make the files managed by your app openable from other apps, +read the Storage Access +Framework guide.

+ + + + + + + + + + + +

Maps

+ +

Show a location on a map

+ +

To open a map, use the {@link android.content.Intent#ACTION_VIEW} action and specify +the location information in the intent data with one of the schemes defined below.

+ +
+
Action
+
{@link android.content.Intent#ACTION_VIEW}
+ +
Data URI Scheme
+
+
+
geo:latitude,longitude
+
Show the map at the given longitude and latitude. +

Example: "geo:47.6,-122.3" +

+
geo:latitude,longitude?z=zoom
+
Show the map at the given longitude and latitude at a certain zoom level. A zoom level of + 1 shows the whole Earth, centered at the given lat,lng. The highest + (closest) zoom level is 23. +

Example: "geo:47.6,-122.3?z=11" +

+
geo:0,0?q=lat,lng(label)
+
Show the map at the given longitude and latitude with a string label. +

Example: "geo:0,0?q=34.99,-106.61(Treasure)" +

+
geo:0,0?q=my+street+address
+
Show the location for "my street address" (may be a specific address or location query). +

Example: "geo:0,0?q=1600+amphitheatre+parkway+ca" +

+
+
+ +
MIME Type
+
None
+ +
+ +

Example intent:

+
+public void showMap(Uri geoLocation) {
+    Intent intent = new Intent(Intent.ACTION_VIEW);
+    intent.setData(geoLocation);
+    if (intent.resolveActivity(getPackageManager()) != null) {
+        startActivity(intent);
+    }
+}
+
+ +

Example intent filter:

+
+<activity ...>
+    <intent-filter>
+        <action android:name="android.intent.action.VIEW" />
+        <data android:scheme="geo" />
+        <category android:name="android.intent.category.DEFAULT" />
+    </intent-filter>
+</activity>
+
+ + + + + + + + +

Music or Video

+ + +

Play a media file

+ +

To play a music file, use the {@link android.content.Intent#ACTION_VIEW} action and +specify the URI location of the file in the intent data.

+ +
+
Action
+
{@link android.content.Intent#ACTION_VIEW}
+ +
Data URI Scheme
+
+
+
{@code file:<URI>} +
{@code content:<URI>} +
{@code http:<URL>} +
+
+ +
MIME Type
+
+
+
"audio/*" +
"application/ogg" +
"application/x-ogg" +
"application/itunes" +
Or any other that your app may require. +
+
+ +
+ +

Example intent:

+
+public void playMedia(Uri file) {
+    Intent intent = new Intent(Intent.ACTION_VIEW);
+    intent.setData(file);
+    if (intent.resolveActivity(getPackageManager()) != null) {
+        startActivity(intent);
+    }
+}
+
+ + +

Example intent filter:

+
+<activity ...>
+    <intent-filter>
+        <action android:name="android.intent.action.VIEW" />
+        <data android:type="audio/*" />
+        <data android:type="application/ogg" />
+        <category android:name="android.intent.category.DEFAULT" />
+    </intent-filter>
+</activity>
+
+ + + + + + + + +

Phone

+ + +

Initiate a phone call

+ +

To open the phone app and dial a phone number, use the {@link +android.content.Intent#ACTION_DIAL} action and specify a phone number using +the URI scheme defined below. When the phone app opens, it displays the phone number +but the user must press the Call button to begin the phone call.

+ + +
+
Action
+
{@link android.content.Intent#ACTION_DIAL}
+ +
Data URI Scheme
+
{@code tel:<phone-number>}
+ +
MIME Type
+
None
+ +
+ + +

Valid telephone numbers are those defined +in the IETF RFC 3966. +Valid examples include the following:

+ +

The Phone's dialer is good at normalizing schemes, such as +telephone numbers. So the scheme described isn't strictly required in the +{@link android.net.Uri#parse(String) Uri.parse()} method. +However, if you have not tried a scheme or are unsure whether it +can be handled, use the {@link android.net.Uri#fromParts Uri.fromParts()} +method instead.

+ + +

Example intent:

+
+public void dialPhoneNumber(String phoneNumber) {
+    Intent intent = new Intent(Intent.ACTION_DIAL);
+    intent.setData(Uri.parse("tel:" + phoneNumber));
+    if (intent.resolveActivity(getPackageManager()) != null) {
+        startActivity(intent);
+    }
+}
+
+ + + + + + + + + + +

Settings

+ +

Open a specific section of Settings

+ +

To open a screen in the system settings when your app requires the user to change something, +use one of the following intent actions to open the settings screen respective to the action name. +

+ +
+
Action
+
+{@link android.provider.Settings#ACTION_SETTINGS}
+{@link android.provider.Settings#ACTION_WIRELESS_SETTINGS}
+{@link android.provider.Settings#ACTION_AIRPLANE_MODE_SETTINGS}
+{@link android.provider.Settings#ACTION_WIFI_SETTINGS}
+{@link android.provider.Settings#ACTION_APN_SETTINGS}
+{@link android.provider.Settings#ACTION_BLUETOOTH_SETTINGS}
+{@link android.provider.Settings#ACTION_DATE_SETTINGS}
+{@link android.provider.Settings#ACTION_LOCALE_SETTINGS}
+{@link android.provider.Settings#ACTION_INPUT_METHOD_SETTINGS}
+{@link android.provider.Settings#ACTION_DISPLAY_SETTINGS}
+{@link android.provider.Settings#ACTION_SECURITY_SETTINGS}
+{@link android.provider.Settings#ACTION_LOCATION_SOURCE_SETTINGS}
+{@link android.provider.Settings#ACTION_INTERNAL_STORAGE_SETTINGS}
+{@link android.provider.Settings#ACTION_MEMORY_CARD_SETTINGS}
+

See the {@link android.provider.Settings} documentation for additional settings screens +that are available.

+
+ +
Data URI Scheme
+
None
+ +
MIME Type
+
None
+ +
+ +

Example intent:

+
+public void openWifiSettings() {
+    Intent intent = new Intent(Intent.ACTION_WIFI_SETTINGS);
+    if (intent.resolveActivity(getPackageManager()) != null) {
+        startActivity(intent);
+    }
+}
+
+ + + + + + + +

Text Messaging

+ +

Compose an SMS/MMS message with attachment

+ +

To initiate an SMS or MMS text message, use one of the intent actions below and specify message +details such as the phone number, subject, and message body using the extra keys listed below.

+ +
+
Action
+
{@link android.content.Intent#ACTION_SENDTO} or
+ {@link android.content.Intent#ACTION_SEND} or
+ {@link android.content.Intent#ACTION_SEND_MULTIPLE}
+ +
Data URI Scheme
+
+
+
{@code sms:<phone_number>} +
{@code smsto:<phone_number>} +
{@code mms:<phone_number>} +
{@code mmsto:<phone_number>} +
+

Each of these schemes are handled the same. +

+ +
MIME Type
+
+
+
{@link org.apache.http.protocol.HTTP#PLAIN_TEXT_TYPE} ("text/plain") +
"image/*" +
"video/*" +
+
+ +
Extras (optional)
+
+
+
"subject"
+
A string for the message subject (usually for MMS only).
+
"sms_body"
+
A string for the text message.
+
{@link android.content.Intent#EXTRA_STREAM}
+
A {@link android.net.Uri} pointing to the +image or video to attach. If using the {@link android.content.Intent#ACTION_SEND_MULTIPLE} action, +this extra should be an {@link java.util.ArrayList} of {@link +android.net.Uri}s pointing to the images/videos to attach.
+
+
+ +
+ +

Example intent:

+
+public void composeMmsMessage(String message, Uri attachment) {
+    Intent intent = new Intent(Intent.ACTION_SEND);
+    intent.setType(HTTP.PLAIN_TEXT_TYPE);
+    intent.putExtra("sms_body", message);
+    intent.putExtra(Intent.EXTRA_STREAM, attachment);
+    if (intent.resolveActivity(getPackageManager()) != null) {
+        startActivity(intent);
+    }
+}
+
+ +

If you want to ensure that your intent is handled only by a text messaging app (and not other +email or social apps), then use the {@link android.content.Intent#ACTION_SENDTO} action +and include the {@code "smsto:"} data scheme. For example:

+ +
+public void composeMmsMessage(String message, Uri attachment) {
+    Intent intent = new Intent(Intent.ACTION_SEND);
+    intent.setData(Uri.parse("smsto:"));  // This ensures only SMS apps respond
+    intent.putExtra("sms_body", message);
+    intent.putExtra(Intent.EXTRA_STREAM, attachment);
+    if (intent.resolveActivity(getPackageManager()) != null) {
+        startActivity(intent);
+    }
+}
+
+ + +

Example intent filter:

+
+<activity ...>
+    <intent-filter>
+        <action android:name="android.intent.action.SEND" />
+        <data android:type="text/plain" />
+        <data android:type="image/*" />
+        <category android:name="android.intent.category.DEFAULT" />
+    </intent-filter>
+</activity>
+
+ +

Note: If you're developing an SMS/MMS messaging app, you must +implement intent filters for several additional actions in order to be available as the +default SMS app on Android 4.4 and higher. For more information, see the documentation +at {@link android.provider.Telephony}.

+ + + + + + + + + + +

Web Browser

+ +

Load a web URL

+ +

To open a web page, use the {@link android.content.Intent#ACTION_VIEW} action +and specify the web URL in the intent data.

+ +
+
Action
+
{@link android.content.Intent#ACTION_VIEW}
+ +
Data URI Scheme
+
{@code http:<URL>}
+ {@code https:<URL>}
+ +
MIME Type
+
+
+
{@link org.apache.http.protocol.HTTP#PLAIN_TEXT_TYPE} ("text/plain") +
"text/html" +
"application/xhtml+xml" +
"application/vnd.wap.xhtml+xml" +
+
+
+ + +

Example intent:

+
+public void openWebPage(String url) {
+    Uri webpage = Uri.parse(url);
+    Intent intent = new Intent(Intent.ACTION_VIEW, webpage);
+    if (intent.resolveActivity(getPackageManager()) != null) {
+        startActivity(intent);
+    }
+}
+
+ + +

Example intent filter:

+
+<activity ...>
+    <intent-filter>
+        <action android:name="android.intent.action.VIEW" />
+        <!-- Include the host attribute if you want your app to respond
+             only to URLs with your app's domain. -->
+        <data android:scheme="http" android:host="www.example.com" />
+        <category android:name="android.intent.category.DEFAULT" />
+        <!-- The BROWSABLE category is required to get links from web pages. -->
+        <category android:name="android.intent.category.BROWSABLE" />
+    </intent-filter>
+</activity>
+
+ + +

Tip: If your Android app provides functionality similar to +your web site, include an intent filter for URLs that point to your web site. Then, +if users have your app installed, links from emails or other web pages pointing to your web site +open your Android app instead of your web page.

+ + + + +

Perform a web search

+ +

To initiate a web search, use the {@link android.content.Intent#ACTION_WEB_SEARCH} action +and specify the search string in the +{@link android.app.SearchManager#QUERY SearchManager.QUERY} extra.

+ + +
+
Action
+
{@link android.content.Intent#ACTION_WEB_SEARCH}
+ +
Data URI Scheme
+
None
+ +
MIME Type
+
None
+ +
Extras
+
+
+
{@link android.app.SearchManager#QUERY SearchManager.QUERY}
+
The search string.
+
+
+
+ +

Example intent:

+
+public void searchWeb(String query) {
+    Intent intent = new Intent(Intent.ACTION_SEARCH);
+    intent.putExtra(SearchManager.QUERY, query);
+    if (intent.resolveActivity(getPackageManager()) != null) {
+        startActivity(intent);
+    }
+}
+
+ + + diff --git a/docs/html/guide/components/intents-filters.jd b/docs/html/guide/components/intents-filters.jd index dfe5fac..2f8c407 100644 --- a/docs/html/guide/components/intents-filters.jd +++ b/docs/html/guide/components/intents-filters.jd @@ -1,4 +1,5 @@ page.title=Intents and Intent Filters +page.tags="IntentFilter" @jd:body
@@ -6,1049 +7,906 @@ page.title=Intents and Intent Filters

In this document

    -
  1. Intent Objects
  2. -
  3. Intent Resolution
  4. -
  5. Intent filters
  6. -
  7. Common cases
  8. -
  9. Using intent matching
  10. -
  11. Note Pad Example
  12. +
  13. Intent Types
  14. +
  15. Building an Intent +
      +
    1. Example explicit intent
    2. +
    3. Example implicit intent
    4. +
    5. Forcing an app chooser
    6. +
    +
  16. +
  17. Receiving an Implicit Intent +
      +
    1. Example filters
    2. +
    +
  18. +
  19. Using a Pending Intent
  20. +
  21. Intent Resolution +
      +
    1. Action test
    2. +
    3. Category test
    4. +
    5. Data test
    6. +
    7. Intent matching
    8. +
    +
-

Key classes

+

See also

    -
  1. {@link android.content.Intent}
  2. -
  3. {@link android.content.IntentFilter}
  4. -
  5. {@link android.content.BroadcastReceiver}
  6. -
  7. {@link android.content.pm.PackageManager}
  8. +
  9. Interacting with Other Apps
  10. +
  11. Sharing Content
-

-Three of the core components of an application — activities, services, and -broadcast receivers — are activated through messages, called intents. -Intent messaging is a facility for late run-time binding between components in the same -or different applications. The intent itself, an {@link android.content.Intent} -object, is a passive data structure holding an abstract description of an operation -to be performed — or, often in the case of broadcasts, a description of something -that has happened and is being announced. There are separate mechanisms for -delivering intents to each type of component: -

+ + +

An {@link android.content.Intent} is a messaging object you can use to request an action +from another app component. +Although intents facilitate communication between components in several ways, there are three +fundamental use-cases:

-

-In each case, the Android system finds the appropriate activity, service, or set -of broadcast receivers to respond to the intent, instantiating them if necessary. -There is no overlap within these messaging systems: Broadcast intents are delivered -only to broadcast receivers, never to activities or services. An intent passed to -{@code startActivity()} is delivered only to an activity, never to a service or -broadcast receiver, and so on. -

-

-This document begins with a description of Intent objects. It then describes the -rules Android uses to map intents to components — how it resolves which -component should receive an intent message. For intents that don't explicitly -name a target component, this process involves testing the Intent object against -intent filters associated with potential targets. -

-

Intent Objects

+

Intent Types

-

-An {@link android.content.Intent} object is a bundle of information. It -contains information of interest to the component that receives the intent -(such as the action to be taken and the data to act on) plus information -of interest to the Android system (such as the category of component that -should handle the intent and instructions on how to launch a target activity). -Principally, it can contain the following: +

There are two types of intents:

+ + + +

When you create an explicit intent to start an activity or service, the system immediately +starts the app component specified in the {@link android.content.Intent} object.

+ +
+ +

Figure 1. Illustration of how an implicit intent is +delivered through the system to start another activity: [1] Activity A creates an +{@link android.content.Intent} with an action description and passes it to {@link +android.content.Context#startActivity startActivity()}. [2] The Android System searches all +apps for an intent filter that matches the intent. When a match is found, [3] the system +starts the matching activity (Activity B) by invoking its {@link +android.app.Activity#onCreate onCreate()} method and passing it the {@link android.content.Intent}.

+
+ +

When you create an implicit intent, the Android system finds the appropriate component to start +by comparing the contents of the intent to the intent filters declared in the manifest file of other apps on the +device. If the intent matches an intent filter, the system starts that component and delivers it +the {@link android.content.Intent} object. If multiple intent filters are compatible, the system +displays a dialog so the user can pick which app to use.

+ +

An intent filter is an expression in an app's manifest file that +specifies the type of intents that the component +would like to receive. For instance, by declaring an intent filter for an activity, +you make it possible for other apps to directly start your activity with a certain kind of intent. +Likewise, if you do not declare any intent filters for an activity, then it can be started +only with an explicit intent.

+ +

Caution: To ensure your app is secure, always use an explicit +intent when starting a {@link android.app.Service} and do not +declare intent filters for your services. Using an implicit intent to start a service is a +security hazard because you cannot be certain what service will respond to the intent, +and the user cannot see which service starts.

+ + + + + +

Building an Intent

+ +

An {@link android.content.Intent} object carries information that the Android system uses +to determine which component to start (such as the exact component name or component +category that should receive the intent), plus information that the recipient component uses in +order to properly perform the action (such as the action to take and the data to act upon).

+ + +

The primary information contained in an {@link android.content.Intent} is the following:

-
Component name
-
The name of the component that should handle the intent. This field is -a {@link android.content.ComponentName} object — a combination of the -fully qualified class name of the target component (for example "{@code -com.example.project.app.FreneticActivity}") and the package name set -in the manifest file of the application where the component resides (for -example, "{@code com.example.project}"). The package part of the component -name and the package name set in the manifest do not necessarily have to match. - -

-The component name is optional. If it is set, the Intent object is -delivered to an instance of the designated class. If it is not set, -Android uses other information in the Intent object to locate a suitable -target — see Intent Resolution, later in this -document. -

+
Component name
+
The name of the component to start. + +

This is optional, but it's the critical piece of information that makes an intent +explicit, meaning that the intent should be delivered only to the app component +defined by the component name. Without a component name, the intent is implicit and the +system decides which component should receive the intent based on the other intent information +(such as the action, data, and category—described below). So if you need to start a specific +component in your app, you should specify the component name.

+ +

Note: When starting a {@link android.app.Service}, you should +always specify the component name. Otherwise, you cannot be certain what service +will respond to the intent, and the user cannot see which service starts.

+ +

This field of the {@link android.content.Intent} is a +{@link android.content.ComponentName} object, which you can specify using a fully +qualified class name of the target component, including the package name of the app. For example, +{@code com.example.ExampleActivity}. You can set the component name with {@link +android.content.Intent#setComponent setComponent()}, {@link android.content.Intent#setClass +setClass()}, {@link android.content.Intent#setClassName(String, String) setClassName()}, or with the +{@link android.content.Intent} constructor.

-

-The component name is set by {@link android.content.Intent#setComponent -setComponent()}, {@link android.content.Intent#setClass -setClass()}, or {@link android.content.Intent#setClassName(String, String) -setClassName()} and read by {@link android.content.Intent#getComponent -getComponent()}. -

Action
-
A string naming the action to be performed — or, in the case of broadcast -intents, the action that took place and is being reported. The Intent class defines -a number of action constants, including these: -

+
A string that specifies the generic action to perform (such as view or pick). - - - - - - - - - - - - - - -
ConstantTarget componentAction
{@code ACTION_CALL} - activity - Initiate a phone call. -
{@code ACTION_EDIT} - activity - Display data for the user to edit. -
{@code ACTION_MAIN} - activity - Start up as the initial activity of a task, with no data input and no returned output. -
{@code ACTION_SYNC} - activity - Synchronize data on a server with data on the mobile device. -
{@code ACTION_BATTERY_LOW} - broadcast receiver - A warning that the battery is low. -
{@code ACTION_HEADSET_PLUG} - broadcast receiver - A headset has been plugged into the device, or unplugged from it. -
{@code ACTION_SCREEN_ON} - broadcast receiver - The screen has been turned on. -
{@code ACTION_TIMEZONE_CHANGED} - broadcast receiver - The setting for the time zone has changed. -
+

In the case of a broadcast intent, this is the action that took place and is being reported. +The action largely determines how the rest of the intent is structured—particularly +what is contained in the data and extras. -

-See the {@link android.content.Intent} class description for a list of -pre-defined constants for generic actions. Other actions are defined -elsewhere in the Android API. -You can also define your own action strings for activating the components -in your application. Those you invent should include the application -package as a prefix — for example: -"com.example.project.SHOW_COLOR". -

+

You can specify your own actions for use by intents within your app (or for use by other +apps to invoke components in your app), but you should usually use action constants +defined by the {@link android.content.Intent} class or other framework classes. Here are some +common actions for starting an activity:

-

-The action largely determines how the rest of the intent is structured -— particularly the data and -extras fields — -much as a method name determines a set of arguments and a return value. -For this reason, it's a good idea to use action names that are -as specific as possible, and to couple them tightly to the other fields of -the intent. In other words, instead of defining an action in isolation, -define an entire protocol for the Intent objects your components can handle. -

+
+
{@link android.content.Intent#ACTION_VIEW}
+
Use this action in an intent with {@link + android.content.Context#startActivity startActivity()} when you have some information that + an activity can show to the user, such as a photo to view in a gallery app, or an address to + view in a map app.
+ +
{@link android.content.Intent#ACTION_SEND}
+
Also known as the "share" intent, you should use this in an intent with {@link + android.content.Context#startActivity startActivity()} when you have some data that the user can + share through another app, such as an email app or social sharing app.
+
-

-The action in an Intent object is set by the -{@link android.content.Intent#setAction setAction()} -method and read by -{@link android.content.Intent#getAction getAction()}. -

-
+

See the {@link android.content.Intent} class reference for more +constants that define generic actions. Other actions are defined +elsewhere in the Android framework, such as in {@link android.provider.Settings} for actions +that open specific screens in the system's Settings app.

-

Data
-
The URI of the data to be acted on and the MIME type of that data. Different -actions are paired with different kinds of data specifications. For example, if -the action field is {@code ACTION_EDIT}, -the data field would contain the URI of the document to be displayed for editing. -If the action is {@code ACTION_CALL}, the data field would be a {@code tel:} URI -with the number to call. Similarly, if the action is {@code ACTION_VIEW} and the -data field is an {@code http:} URI, the receiving activity would be called upon -to download and display whatever data the URI refers to. +

You can specify the action for an intent with {@link android.content.Intent#setAction +setAction()} or with an {@link android.content.Intent} constructor.

-

-When matching an intent to a component that is capable of handling the data, -it's often important to know the type of data (its MIME type) in addition to its URI. -For example, a component able to display image data should not be called -upon to play an audio file. -

+

If you define your own actions, be sure to include your app's package name +as a prefix. For example:

+
static final String ACTION_TIMETRAVEL = "com.example.action.TIMETRAVEL";
+
-

-In many cases, the data type can be inferred from the URI — particularly -{@code content:} URIs, which indicate that the data is located on the device and -controlled by a content provider (see the -separate -discussion on content providers). But the type can also be explicitly set -in the Intent object. -The {@link android.content.Intent#setData setData()} method specifies -data only as a URI, {@link android.content.Intent#setType setType()} -specifies it only as a MIME type, and {@link -android.content.Intent#setDataAndType setDataAndType()} specifies it as both -a URI and a MIME type. The URI is read by {@link -android.content.Intent#getData getData()} and the type by {@link -android.content.Intent#getType getType()}. -

+
Data
+
The URI (a {@link android.net.Uri} object) that references the data to be acted on and/or the +MIME type of that data. The type of data supplied is generally dictated by the intent's action. For +example, if the action is {@link android.content.Intent#ACTION_EDIT}, the data should contain the +URI of the document to edit. + +

When creating an intent, +it's often important to specify the type of data (its MIME type) in addition to its URI. +For example, an activity that's able to display images probably won't be able +to play an audio file, even though the URI formats could be similar. +So specifying the MIME type of your data helps the Android +system find the best component to receive your intent. +However, the MIME type can sometimes be inferred from the URI—particularly when the data is a +{@code content:} URI, which indicates the data is located on the device and controlled by a +{@link android.content.ContentProvider}, which makes the data MIME type visible to the system.

+ +

To set only the data URI, call {@link android.content.Intent#setData setData()}. +To set only the MIME type, call {@link android.content.Intent#setType setType()}. If necessary, you +can set both explicitly with {@link +android.content.Intent#setDataAndType setDataAndType()}.

+ +

Caution: If you want to set both the URI and MIME type, +do not call {@link android.content.Intent#setData setData()} and +{@link android.content.Intent#setType setType()} because they each nullify the value of the other. +Always use {@link android.content.Intent#setDataAndType setDataAndType()} to set both +URI and MIME type.

Category
-
A string containing additional information about the kind of component -that should handle the intent. Any number of category descriptions can be -placed in an Intent object. As it does for actions, the Intent class defines -several category constants, including these: - - - - - - - - - - - -
ConstantMeaning
{@code CATEGORY_BROWSABLE} - The target activity can be safely invoked by the browser to display data - referenced by a link — for example, an image or an e-mail message. -
{@code CATEGORY_GADGET} - The activity can be embedded inside of another activity that hosts gadgets. -
{@code CATEGORY_HOME} - The activity displays the home screen, the first screen the user sees when - the device is turned on or when the Home button is pressed. -
{@code CATEGORY_LAUNCHER} - The activity can be the initial activity of a task and is listed in - the top-level application launcher. -
{@code CATEGORY_PREFERENCE} - The target activity is a preference panel. -
+
A string containing additional information about the kind of component +that should handle the intent. Any number of category descriptions can be +placed in an intent, but most intents do not require a category. +Here are some common categories: -

-See the {@link android.content.Intent} class description for the full list of -categories. -

+
+
{@link android.content.Intent#CATEGORY_BROWSABLE}
+
The target activity allows itself to be started by a web browser to display data + referenced by a link—such as an image or an e-mail message. +
+
{@link android.content.Intent#CATEGORY_LAUNCHER}
+
The activity is the initial activity of a task and is listed in + the system's application launcher. +
+
-

-The {@link android.content.Intent#addCategory addCategory()} method -places a category in an Intent object, {@link android.content.Intent#removeCategory -removeCategory()} deletes a category previously added, and {@link android.content.Intent#getCategories getCategories()} gets the set of all -categories currently in the object. -

+

See the {@link android.content.Intent} class description for the full list of +categories.

+ +

You can specify a category with {@link android.content.Intent#addCategory addCategory()}.

+
-

Extras
-
Key-value pairs for additional information that should be delivered to the -component handling the intent. Just as some actions are paired with particular -kinds of data URIs, some are paired with particular extras. For example, an -{@code ACTION_TIMEZONE_CHANGED} intent has a "{@code time-zone}" extra that -identifies the new time zone, and {@code ACTION_HEADSET_PLUG} has a -"{@code state}" extra indicating whether the headset is now plugged in or -unplugged, as well as a "{@code name}" extra for the type of headset. -If you were to invent a {@code SHOW_COLOR} action, the color value would -be set in an extra key-value pair. -

-The Intent object has a series of {@code put...()} methods for inserting various -types of extra data and a similar set of {@code get...()} methods for reading -the data. These methods parallel those for {@link android.os.Bundle} objects. -In fact, the extras can be installed and read as a Bundle using the {@link -android.content.Intent#putExtras putExtras()} and {@link -android.content.Intent#getExtras getExtras()} methods. -

+

These properties listed above (component name, action, data, and category) represent the +defining characteristics of an intent. By reading these properties, the Android system +is able to resolve which app component it should start.

+ +

However, an intent can carry additional information that does not affect +how it is resolved to an app component. An intent can also supply:

+ +
+
Extras
+
Key-value pairs that carry additional information required to accomplish the requested action. +Just as some actions use particular kinds of data URIs, some actions also use particular extras. + +

You can add extra data with various {@link android.content.Intent#putExtra putExtra()} methods, +each accepting two parameters: the key name and the value. +You can also create a {@link android.os.Bundle} object with all the extra data, then insert +the {@link android.os.Bundle} in the {@link android.content.Intent} with {@link +android.content.Intent#putExtras putExtras()}.

+ +

For example, when creating an intent to send an email with +{@link android.content.Intent#ACTION_SEND}, you can specify the "to" recipient with the +{@link android.content.Intent#EXTRA_EMAIL} key, and specify the "subject" with the +{@link android.content.Intent#EXTRA_SUBJECT} key.

+ +

The {@link android.content.Intent} class specifies many {@code EXTRA_*} constants +for standardized data types. If you need to declare your own extra keys (for intents that +your app receives), be sure to include your app's package name +as a prefix. For example:

+
static final String EXTRA_GIGAWATTS = "com.example.EXTRA_GIGAWATTS";
-

Flags
-
Flags of various sorts. Many instruct the Android system how to launch an -activity (for example, which task the activity should belong to) and how to treat -it after it's launched (for example, whether it belongs in the list of recent -activities). All these flags are defined in the Intent class. +
Flags
+
Flags defined in the {@link android.content.Intent} class that function as metadata for the +intent. The flags may instruct the Android system how to launch an activity (for example, which +task the activity should belong +to) and how to treat it after it's launched (for example, whether it belongs in the list of recent +activities). + +

For more information, see the {@link android.content.Intent#setFlags setFlags()} method.

-

-The Android system and the applications that come with the platform employ -Intent objects both to send out system-originated broadcasts and to activate -system-defined components. To see how to structure an intent to activate a -system component, consult the -list of intents -in the reference. -

-

Intent Resolution

-

-Intents can be divided into two groups: -

+

Example explicit intent

- +

An explicit intent is one that you use to launch a specific app component, such as +a particular activity or service in your app. To create an explicit intent, define +the component name for the {@link android.content.Intent} object—all +other intent properties are optional.

-

-Android delivers an explicit intent to an instance of the designated -target class. Nothing in the Intent object other than the component -name matters for determining which component should get the intent. -

+

For example, if you built a service in your app, named {@code DownloadService}, +designed to download a file from the web, you can start it with the following code:

-

-A different strategy is needed for implicit intents. In the absence of a -designated target, the Android system must find the best component (or -components) to handle the intent — a single activity or service to -perform the requested action or the set of broadcast receivers to respond -to the broadcast announcement. It does so by comparing the contents of -the Intent object to intent filters, structures associated with -components that can potentially receive intents. Filters advertise the -capabilities of a component and delimit the intents it can handle. They -open the component to the possibility of receiving implicit intents of -the advertised type. If a component does not have any intent filters, -it can receive only explicit intents. A component with filters can -receive both explicit and implicit intents. -

+
+// Executed in an Activity, so 'this' is the {@link android.content.Context}
+// The fileUrl is a string URL, such as "http://www.example.com/image.png"
+Intent downloadIntent = new Intent(this, DownloadService.class);
+downloadIntent.setData({@link android.net.Uri#parse Uri.parse}(fileUrl));
+startService(downloadIntent);
+
-

-Only three aspects of an Intent object are consulted when the object -is tested against an intent filter: -

+

The {@link android.content.Intent#Intent(Context,Class)} +constructor supplies the app {@link android.content.Context} and the +component a {@link java.lang.Class} object. As such, +this intent explicitly starts the {@code DownloadService} class in the app.

-

action -
data (both URI and data type) -
category

+

For more information about building and starting a service, see the +Services guide.

-

-The extras and flags play no part in resolving which component receives -an intent. -

-

Intent filters

-

-To inform the system which implicit intents they can handle, activities, -services, and broadcast receivers can have one or more intent filters. -Each filter describes a capability of the component, a set of intents that -the component is willing to receive. It, in effect, filters in -intents of a desired type, while filtering out unwanted -intents — but only unwanted implicit intents (those that don't name -a target class). An explicit intent is always delivered to its target, -no matter what it contains; the filter is not consulted. But an implicit -intent is delivered to a component only if it can pass through one of the -component's filters. -

+

Example implicit intent

-

-A component has separate filters for each job it can do, each face it can -present to the user. For example, the NoteEditor activity of the sample -Note Pad application has two filters — one for starting up with a -specific note that the user can view or edit, and another for starting -with a new, blank note that the user can fill in and save. (All of Note -Pad's filters are described in the Note Pad Example -section, later.) -

+

An implicit intent specifies an action that can invoke any app on the device able +to perform the action. Using an implicit intent is useful when your app cannot perform the +action, but other apps probably can and you'd like the user to pick which app to use.

-
introduced in:
diff --git a/docs/html/images/components/intent-filters@2x.png b/docs/html/images/components/intent-filters@2x.png new file mode 100644 index 0000000..5b1e38b Binary files /dev/null and b/docs/html/images/components/intent-filters@2x.png differ diff --git a/docs/html/training/basics/intents/filters.jd b/docs/html/training/basics/intents/filters.jd index 9b6a111..10bf43d 100644 --- a/docs/html/training/basics/intents/filters.jd +++ b/docs/html/training/basics/intents/filters.jd @@ -148,8 +148,8 @@ the recipient's address using the {@code send} or {@code sendto} URI scheme. For {@link android.content.Intent#CATEGORY_DEFAULT} category in the intent filter. The methods {@link android.app.Activity#startActivity startActivity()} and {@link android.app.Activity#startActivityForResult startActivityForResult()} treat all intents as if they -contained the {@link android.content.Intent#CATEGORY_DEFAULT} category. If you do not declare it, no -implicit intents will resolve to your activity.

+declared the {@link android.content.Intent#CATEGORY_DEFAULT} category. If you do not declare it +in your intent filter, no implicit intents will resolve to your activity.

For more information about sending and receiving {@link android.content.Intent#ACTION_SEND} intents that perform social sharing behaviors, see the lesson about

This displays a dialog with a list of apps that respond to the intent passed to the {@link diff --git a/docs/html/training/sharing/send.jd b/docs/html/training/sharing/send.jd index f5da68f..e869d5f 100644 --- a/docs/html/training/sharing/send.jd +++ b/docs/html/training/sharing/send.jd @@ -75,10 +75,12 @@ startActivity(sendIntent);

If there's an installed application with a filter that matches {@link android.content.Intent#ACTION_SEND} and MIME type text/plain, the Android system will run it; if more than one application matches, the system displays a disambiguation dialog (a "chooser") -that allows the user to choose an app. If you call +that allows the user to choose an app.

+ +

However, if you call {@link android.content.Intent#createChooser(android.content.Intent, CharSequence) -Intent.createChooser()} -for the intent, Android will always display the chooser. This has some +Intent.createChooser()}, passing it your {@link android.content.Intent} object, it returns a version +of your intent that will always display the chooser. This has some advantages: