intents-filters.jd revision 9adc33a6584d4fcc1c692cabc2bb97498875e89a
1page.title=Intents and Intent Filters
2page.tags="IntentFilter"
3@jd:body
4
5<div id="qv-wrapper">
6<div id="qv">
7
8<h2>In this document</h2>
9<ol>
10  <li><a href="#Types">Intent Types</a></li>
11  <li><a href="#Building">Building an Intent</a>
12    <ol>
13      <li><a href="#ExampleExplicit">Example explicit intent</a></li>
14      <li><a href="#ExampleSend">Example implicit intent</a></li>
15      <li><a href="#ForceChooser">Forcing an app chooser</a></li>
16    </ol>
17  </li>
18  <li><a href="#Receiving">Receiving an Implicit Intent</a>
19    <ol>
20      <li><a href="#ExampleFilters">Example filters</a></li>
21    </ol>
22  </li>
23  <li><a href="#PendingIntent">Using a Pending Intent</a></li>
24  <li><a href="#Resolution">Intent Resolution</a>
25    <ol>
26      <li><a href="#ActionTest">Action test</a></li>
27      <li><a href="#CategoryTest">Category test</a></li>
28      <li><a href="#DataTest">Data test</a></li>
29      <li><a href="#imatch">Intent matching</a></li>
30    </ol>
31  </li>
32</ol>
33
34<h2>See also</h2>
35<ol>
36<li><a href="{@docRoot}training/basics/intents/index.html">Interacting with Other Apps</a></li>
37<li><a href="{@docRoot}training/sharing/index.html">Sharing Content</a></li>
38</ol>
39
40</div>
41</div>
42
43
44
45
46<p>An {@link android.content.Intent} is a messaging object you can use to request an action
47from another <a href="{@docRoot}guide/components/fundamentals.html#Components">app component</a>.
48Although intents facilitate communication between components in several ways, there are three
49fundamental use-cases:</p>
50
51<ul>
52<li><b>To start an activity:</b>
53<p>An {@link android.app.Activity} represents a single screen in an app. You can start a new
54instance of an {@link android.app.Activity} by passing an {@link android.content.Intent}
55to {@link android.content.Context#startActivity startActivity()}. The {@link android.content.Intent}
56describes the activity to start and carries any necessary data.</p>
57
58<p>If you want to receive a result from the activity when it finishes,
59call {@link android.app.Activity#startActivityForResult
60startActivityForResult()}. Your activity receives the result
61as a separate {@link android.content.Intent} object in your activity's {@link
62android.app.Activity#onActivityResult onActivityResult()} callback.
63For more information, see the <a
64href="{@docRoot}guide/components/activities.html">Activities</a> guide.</p></li>
65
66<li><b>To start a service:</b>
67<p>A {@link android.app.Service} is a component that performs operations in the background
68without a user interface. You can start a service to perform a one-time operation
69(such as download a file) by passing an {@link android.content.Intent}
70to {@link android.content.Context#startService startService()}. The {@link android.content.Intent}
71describes the service to start and carries any necessary data.</p>
72
73<p>If the service is designed with a client-server interface, you can bind to the service
74from another component by passing an {@link android.content.Intent} to {@link
75android.content.Context#bindService bindService()}</code>. For more information, see the <a
76href="{@docRoot}guide/components/services.html">Services</a> guide.</p></li>
77
78<li><b>To deliver a broadcast:</b>
79<p>A broadcast is a message that any app can receive. The system delivers various
80broadcasts for system events, such as when the system boots up or the device starts charging.
81You can deliver a broadcast to other apps by passing an {@link android.content.Intent}
82to {@link android.content.Context#sendBroadcast(Intent) sendBroadcast()},
83{@link android.content.Context#sendOrderedBroadcast(Intent, String)
84sendOrderedBroadcast()}, or {@link
85android.content.Context#sendStickyBroadcast sendStickyBroadcast()}.</p>
86</li>
87</ul>
88
89
90
91
92<h2 id="Types">Intent Types</h2>
93
94<p>There are two types of intents:</p>
95
96<ul>
97<li><b>Explicit intents</b> specify the component to start by name (the
98fully-qualified class name). You'll typically use an explicit intent to start a component in
99your own app, because you know the class name of the activity or service you want to start. For
100example, start a new activity in response to a user action or start a service to download
101a file in the background.</li>
102
103<li><b>Implicit intents</b> do not name a specific component, but instead declare a general action
104to perform, which allows a component from another app to handle it. For example, if you want to
105show the user a location on a map, you can use an implicit intent to request that another capable
106app show a specified location on a map.</li>
107</ul>
108
109<p>When you create an explicit intent to start an activity or service, the system immediately
110starts the app component specified in the {@link android.content.Intent} object.</p>
111
112<div class="figure" style="width:446px">
113<img src="{@docRoot}images/components/intent-filters@2x.png" width="446" alt=""/>
114<p class="img-caption"><strong>Figure 1.</strong> Illustration of how an implicit intent is
115delivered through the system to start another activity: <b>[1]</b> <em>Activity A</em> creates an
116{@link android.content.Intent} with an action description and passes it to {@link
117android.content.Context#startActivity startActivity()}. <b>[2]</b> The Android System searches all
118apps for an intent filter that matches the intent. When a match is found, <b>[3]</b> the system
119starts the matching activity (<em>Activity B</em>) by invoking its {@link
120android.app.Activity#onCreate onCreate()} method and passing it the {@link android.content.Intent}.
121</p>
122</div>
123
124<p>When you create an implicit intent, the Android system finds the appropriate component to start
125by comparing the contents of the intent to the <em>intent filters</em> declared in the <a href=
126"{@docRoot}guide/topics/manifest/manifest-intro.html">manifest file</a> of other apps on the
127device. If the intent matches an intent filter, the system starts that component and delivers it
128the {@link android.content.Intent} object. If multiple intent filters are compatible, the system
129displays a dialog so the user can pick which app to use.</p>
130
131<p>An intent filter is an expression in an app's manifest file that
132specifies the type of intents that the component
133would like to receive. For instance, by declaring an intent filter for an activity,
134you make it possible for other apps to directly start your activity with a certain kind of intent.
135Likewise, if you do <em>not</em> declare any intent filters for an activity, then it can be started
136only with an explicit intent.</p>
137
138<p class="caution"><strong>Caution:</strong> To ensure your app is secure, always use an explicit
139intent when starting a {@link android.app.Service} and do not
140declare intent filters for your services. Using an implicit intent to start a service is a
141security hazard because you cannot be certain what service will respond to the intent,
142and the user cannot see which service starts. Beginning with Android 5.0 (API level 21), the system
143throws an exception if you call {@link android.content.Context#bindService bindService()}
144with an implicit intent.</p>
145
146
147
148
149
150<h2 id="Building">Building an Intent</h2>
151
152<p>An {@link android.content.Intent} object carries information that the Android system uses
153to determine which component to start (such as the exact component name or component
154category that should receive the intent), plus information that the recipient component uses in
155order to properly perform the action (such as the action to take and the data to act upon).</p>
156
157
158<p>The primary information contained in an {@link android.content.Intent} is the following:</p>
159
160<dl>
161
162<dt><b>Component name</b></dt>
163<dd>The name of the component to start.
164
165<p>This is optional, but it's the critical piece of information that makes an intent
166<b>explicit</b>, meaning that the intent should be delivered only to the app component
167defined by the component name. Without a component name, the intent is <b>implicit</b> and the
168system decides which component should receive the intent based on the other intent information
169(such as the action, data, and category&mdash;described below). So if you need to start a specific
170component in your app, you should specify the component name.</p>
171
172<p class="note"><strong>Note:</strong> When starting a {@link android.app.Service}, you should
173<strong>always specify the component name</strong>. Otherwise, you cannot be certain what service
174will respond to the intent, and the user cannot see which service starts.</p>
175
176<p>This field of the {@link android.content.Intent} is a
177{@link android.content.ComponentName} object, which you can specify using a fully
178qualified class name of the target component, including the package name of the app. For example,
179{@code com.example.ExampleActivity}. You can set the component name with {@link
180android.content.Intent#setComponent setComponent()}, {@link android.content.Intent#setClass
181setClass()}, {@link android.content.Intent#setClassName(String, String) setClassName()}, or with the
182{@link android.content.Intent} constructor.</p>
183
184</dd>
185
186<p><dt><b>Action</b></dt>
187<dd>A string that specifies the generic action to perform (such as <em>view</em> or <em>pick</em>).
188
189<p>In the case of a broadcast intent, this is the action that took place and is being reported.
190The action largely determines how the rest of the intent is structured&mdash;particularly
191what is contained in the data and extras.
192
193<p>You can specify your own actions for use by intents within your app (or for use by other
194apps to invoke components in your app), but you should usually use action constants
195defined by the {@link android.content.Intent} class or other framework classes. Here are some
196common actions for starting an activity:</p>
197
198<dl>
199<dt>{@link android.content.Intent#ACTION_VIEW}</dt>
200   <dd>Use this action in an intent with {@link
201   android.content.Context#startActivity startActivity()} when you have some information that
202   an activity can show to the user, such as a photo to view in a gallery app, or an address to
203   view in a map app.</dd>
204
205<dt>{@link android.content.Intent#ACTION_SEND}</dt>
206   <dd>Also known as the "share" intent, you should use this in an intent with {@link
207   android.content.Context#startActivity startActivity()} when you have some data that the user can
208   share through another app, such as an email app or social sharing app.</dd>
209</dl>
210
211<p>See the {@link android.content.Intent} class reference for more
212constants that define generic actions.  Other actions are defined
213elsewhere in the Android framework, such as in {@link android.provider.Settings} for actions
214that open specific screens in the system's Settings app.</p>
215
216<p>You can specify the action for an intent with {@link android.content.Intent#setAction
217setAction()} or with an {@link android.content.Intent} constructor.</p>
218
219<p>If you define your own actions, be sure to include your app's package name
220as a prefix. For example:</p>
221<pre>static final String ACTION_TIMETRAVEL = "com.example.action.TIMETRAVEL";</pre>
222</dd>
223
224<dt><b>Data</b></dt>
225<dd>The URI (a {@link android.net.Uri} object) that references the data to be acted on and/or the
226MIME type of that data. The type of data supplied is generally dictated by the intent's action. For
227example, if the action is {@link android.content.Intent#ACTION_EDIT}, the data should contain the
228URI of the document to edit.
229
230<p>When creating an intent,
231it's often important to specify the type of data (its MIME type) in addition to its URI.
232For example, an activity that's able to display images probably won't be able
233to play an audio file, even though the URI formats could be similar.
234So specifying the MIME type of your data helps the Android
235system find the best component to receive your intent.
236However, the MIME type can sometimes be inferred from the URI&mdash;particularly when the data is a
237{@code content:} URI, which indicates the data is located on the device and controlled by a
238{@link android.content.ContentProvider}, which makes the data MIME type visible to the system.</p>
239
240<p>To set only the data URI, call {@link android.content.Intent#setData setData()}.
241To set only the MIME type, call {@link android.content.Intent#setType setType()}. If necessary, you
242can set both explicitly with {@link
243android.content.Intent#setDataAndType setDataAndType()}.</p>
244
245<p class="caution"><strong>Caution:</strong> If you want to set both the URI and MIME type,
246<strong>do not</strong> call {@link android.content.Intent#setData setData()} and
247{@link android.content.Intent#setType setType()} because they each nullify the value of the other.
248Always use {@link android.content.Intent#setDataAndType setDataAndType()} to set both
249URI and MIME type.</p>
250</dd>
251
252<p><dt><b>Category</b></dt>
253<dd>A string containing additional information about the kind of component
254that should handle the intent.  Any number of category descriptions can be
255placed in an intent, but most intents do not require a category.
256Here are some common categories:
257
258<dl>
259<dt>{@link android.content.Intent#CATEGORY_BROWSABLE}</dt>
260  <dd>The target activity allows itself to be started by a web browser to display data
261       referenced by a link&mdash;such as an image or an e-mail message.
262  </dd>
263<dt>{@link android.content.Intent#CATEGORY_LAUNCHER}</dt>
264  <dd>The activity is the initial activity of a task and is listed in
265       the system's application launcher.
266  </dd>
267</dl>
268
269<p>See the {@link android.content.Intent} class description for the full list of
270categories.</p>
271
272<p>You can specify a category with {@link android.content.Intent#addCategory addCategory()}.</p>
273</dd>
274</dl>
275
276
277<p>These properties listed above (component name, action, data, and category) represent the
278defining characteristics of an intent. By reading these properties, the Android system
279is able to resolve which app component it should start.</p>
280
281<p>However, an intent can carry additional information that does not affect
282how it is resolved to an app component. An intent can also supply:</p>
283
284<dl>
285<dt><b>Extras</b></dt>
286<dd>Key-value pairs that carry additional information required to accomplish the requested action.
287Just as some actions use particular kinds of data URIs, some actions also use particular extras.
288
289<p>You can add extra data with various {@link android.content.Intent#putExtra putExtra()} methods,
290each accepting two parameters: the key name and the value.
291You can also create a {@link android.os.Bundle} object with all the extra data, then insert
292the {@link android.os.Bundle} in the {@link android.content.Intent} with {@link
293android.content.Intent#putExtras putExtras()}.</p>
294
295<p>For example, when creating an intent to send an email with
296{@link android.content.Intent#ACTION_SEND}, you can specify the "to" recipient with the
297{@link android.content.Intent#EXTRA_EMAIL} key, and specify the "subject" with the
298{@link android.content.Intent#EXTRA_SUBJECT} key.</p>
299
300<p>The {@link android.content.Intent} class specifies many {@code EXTRA_*} constants
301for standardized data types. If you need to declare your own extra keys (for intents that
302your app receives), be sure to include your app's package name
303as a prefix. For example:</p>
304<pre>static final String EXTRA_GIGAWATTS = "com.example.EXTRA_GIGAWATTS";</pre>
305</dd>
306
307<dt><b>Flags</b></dt>
308<dd>Flags defined in the {@link android.content.Intent} class that function as metadata for the
309intent. The flags may instruct the Android system how to launch an activity (for example, which
310<a href="{@docRoot}guide/components/tasks-and-back-stack.html">task</a> the activity should belong
311to) and how to treat it after it's launched (for example, whether it belongs in the list of recent
312activities).
313
314<p>For more information, see the {@link android.content.Intent#setFlags setFlags()} method.</p>
315</dd>
316
317</dl>
318
319
320
321
322<h3 id="ExampleExplicit">Example explicit intent</h3>
323
324<p>An explicit intent is one that you use to launch a specific app component, such as
325a particular activity or service in your app. To create an explicit intent, define
326the component name for the {@link android.content.Intent} object&mdash;all
327other intent properties are optional.</p>
328
329<p>For example, if you built a service in your app, named {@code DownloadService},
330designed to download a file from the web, you can start it with the following code:</p>
331
332<pre>
333// Executed in an Activity, so 'this' is the {@link android.content.Context}
334// The fileUrl is a string URL, such as "http://www.example.com/image.png"
335Intent downloadIntent = new Intent(this, DownloadService.class);
336downloadIntent.setData({@link android.net.Uri#parse Uri.parse}(fileUrl));
337startService(downloadIntent);
338</pre>
339
340<p>The {@link android.content.Intent#Intent(Context,Class)}
341constructor supplies the app {@link android.content.Context} and the
342component a {@link java.lang.Class} object. As such,
343this intent explicitly starts the {@code DownloadService} class in the app.</p>
344
345<p>For more information about building and starting a service, see the
346<a href="{@docRoot}guide/components/services.html">Services</a> guide.</p>
347
348
349
350
351<h3 id="ExampleSend">Example implicit intent</h3>
352
353<p>An implicit intent specifies an action that can invoke any app on the device able
354to perform the action. Using an implicit intent is useful when your app cannot perform the
355action, but other apps probably can and you'd like the user to pick which app to use.</p>
356
357<p>For example, if you have content you want the user to share with other people, create an intent
358with the {@link android.content.Intent#ACTION_SEND} action
359and add extras that specify the content to share. When you call
360{@link android.content.Context#startActivity startActivity()} with that intent, the user can
361pick an app through which to share the content.</p>
362
363<p class="caution"><strong>Caution:</strong> It's possible that a user won't have <em>any</em>
364apps that handle the implicit intent you send to {@link android.content.Context#startActivity
365startActivity()}. If that happens, the call will fail and your app will crash. To verify
366that an activity will receive the intent, call {@link android.content.Intent#resolveActivity
367resolveActivity()} on your {@link android.content.Intent} object. If the result is non-null,
368then there is at least one app that can handle the intent and it's safe to call
369{@link android.content.Context#startActivity startActivity()}. If the result is null,
370you should not use the intent and, if possible, you should disable the feature that issues
371the intent.</p>
372
373
374<pre>
375// Create the text message with a string
376Intent sendIntent = new Intent();
377sendIntent.setAction(Intent.ACTION_SEND);
378sendIntent.putExtra(Intent.EXTRA_TEXT, textMessage);
379sendIntent.setType({@link
380        org.apache.http.protocol.HTTP#PLAIN_TEXT_TYPE
381        HTTP.PLAIN_TEXT_TYPE}); // "text/plain" MIME type
382
383// Verify that the intent will resolve to an activity
384if (sendIntent.resolveActivity(getPackageManager()) != null) {
385    startActivity(sendIntent);
386}
387</pre>
388
389<p class="note"><strong>Note:</strong> In this case, a URI is not used, but the intent's data type
390is declared to specify the content carried by the extras.</p>
391
392
393<p>When {@link android.content.Context#startActivity startActivity()} is called, the system
394examines all of the installed apps to determine which ones can handle this kind of intent (an
395intent with the {@link android.content.Intent#ACTION_SEND} action and that carries "text/plain"
396data). If there's only one app that can handle it, that app opens immediately and is given the
397intent. If multiple activities accept the intent, the system
398displays a dialog so the user can pick which app to use..</p>
399
400
401<div class="figure" style="width:200px">
402  <img src="{@docRoot}images/training/basics/intent-chooser.png" alt="">
403  <p class="img-caption"><strong>Figure 2.</strong> A chooser dialog.</p>
404</div>
405
406<h3 id="ForceChooser">Forcing an app chooser</h3>
407
408<p>When there is more than one app that responds to your implicit intent,
409the user can select which app to use and make that app the default choice for the
410action. This is nice when performing an action for which the user
411probably wants to use the same app from now on, such as when opening a web page (users
412often prefer just one web browser) .</p>
413
414<p>However, if multiple apps can respond to the intent and the user might want to use a different
415app each time, you should explicitly show a chooser dialog. The chooser dialog asks the
416user to select which app to use for the action every time (the user cannot select a default app for
417the action). For example, when your app performs "share" with the {@link
418android.content.Intent#ACTION_SEND} action, users may want to share using a different app depending
419on their current situation, so you should always use the chooser dialog, as shown in figure 2.</p>
420
421
422
423
424<p>To show the chooser, create an {@link android.content.Intent} using {@link
425android.content.Intent#createChooser createChooser()} and pass it to {@link
426android.app.Activity#startActivity startActivity()}. For example:</p>
427
428<pre>
429Intent sendIntent = new Intent(Intent.ACTION_SEND);
430...
431
432// Always use string resources for UI text.
433// This says something like "Share this photo with"
434String title = getResources().getString(R.string.chooser_title);
435// Create intent to show the chooser dialog
436Intent chooser = Intent.createChooser(sendIntent, title);
437
438// Verify the original intent will resolve to at least one activity
439if (sendIntent.resolveActivity(getPackageManager()) != null) {
440    startActivity(chooser);
441}
442</pre>
443
444<p>This displays a dialog with a list of apps that respond to the intent passed to the {@link
445android.content.Intent#createChooser createChooser()} method and uses the supplied text as the
446dialog title.</p>
447
448
449
450
451
452
453
454
455
456<h2 id="Receiving">Receiving an Implicit Intent</h2>
457
458<p>To advertise which implicit intents your app can receive, declare one or more intent filters for
459each of your app components with an <a href=
460"{@docRoot}guide/topics/manifest/intent-filter-element.html">{@code &lt;intent-filter&gt;}</a>
461element in your <a href="{@docRoot}guide/topics/manifest/manifest-intro.html">manifest file</a>.
462Each intent filter specifies the type of intents it accepts based on the intent's action,
463data, and category. The system will deliver an implicit intent to your app component only if the
464intent can pass through one of your intent filters.</p>
465
466<p class="note"><strong>Note:</strong> An explicit intent is always delivered to its target,
467regardless of any intent filters the component declares.</p>
468
469<p>An app component should declare separate filters for each unique job it can do.
470For example, one activity in an image gallery app may have two filters: one filter
471to view an image, and another filter to edit an image. When the activity starts,
472it inspects the {@link android.content.Intent} and decides how to behave based on the information
473in the {@link android.content.Intent} (such as to show the editor controls or not).</p>
474
475<p>Each intent filter is defined by an <a
476href="{@docRoot}guide/topics/manifest/intent-filter-element.html">{@code &lt;intent-filter>}</a>
477element in the app's manifest file, nested in the corresponding app component (such
478as an <a href="{@docRoot}guide/topics/manifest/activity-element.html">{@code &lt;activity>}</a>
479element). Inside the <a
480href="{@docRoot}guide/topics/manifest/intent-filter-element.html">{@code &lt;intent-filter>}</a>,
481you can specify the type of intents to accept using one or more
482of these three elements:</p>
483
484<dl>
485<dt><a href="{@docRoot}guide/topics/manifest/action-element.html">{@code &lt;action>}</a></dt>
486  <dd>Declares the intent action accepted, in the {@code name} attribute. The value
487  must be the literal string value of an action, not the class constant.</dd>
488<dt><a href="{@docRoot}guide/topics/manifest/data-element.html">{@code &lt;data>}</a></dt>
489  <dd>Declares the type of data accepted, using one or more attributes that specify various
490  aspects of the data URI (<code>scheme</code>, <code>host</code>, <code>port</code>,
491  <code>path</code>, etc.) and MIME type.</dd>
492<dt><a href="{@docRoot}guide/topics/manifest/category-element.html">{@code &lt;category>}</a></dt>
493  <dd>Declares the intent category accepted, in the {@code name} attribute. The value
494  must be the literal string value of an action, not the class constant.
495
496  <p class="note"><strong>Note:</strong> In order to receive implicit intents, you
497  <strong>must include</strong> the
498  {@link android.content.Intent#CATEGORY_DEFAULT} category in the intent filter. The methods
499  {@link android.app.Activity#startActivity startActivity()} and
500  {@link android.app.Activity#startActivityForResult startActivityForResult()} treat all intents
501  as if they declared the {@link android.content.Intent#CATEGORY_DEFAULT} category.
502  If you do not declare this category in your intent filter, no implicit intents will resolve to
503  your activity.</p>
504  </dd>
505</dl>
506
507<p>For example, here's an activity declaration with an intent filter to receive an
508{@link android.content.Intent#ACTION_SEND} intent when the data type is text:</p>
509
510<pre>
511&lt;activity android:name="ShareActivity">
512    &lt;intent-filter>
513        &lt;action android:name="android.intent.action.SEND"/>
514        &lt;category android:name="android.intent.category.DEFAULT"/>
515        &lt;data android:mimeType="text/plain"/>
516    &lt;/intent-filter>
517&lt;/activity>
518</pre>
519
520<p>It's okay to create a filter that includes more than one instance of
521<a href="{@docRoot}guide/topics/manifest/action-element.html">{@code &lt;action>}</a>,
522<a href="{@docRoot}guide/topics/manifest/data-element.html">{@code &lt;data>}</a>, or
523<a href="{@docRoot}guide/topics/manifest/category-element.html">{@code &lt;category>}</a>.
524If you do, you simply need to be certain that the component can handle any and all combinations
525of those filter elements.</p>
526
527<p>When you want to handle multiple kinds of intents, but only in specific combinations of
528action, data, and category type, then you need to create multiple intent filters.</p>
529
530
531<div class="sidebox-wrapper">
532<div class="sidebox">
533<h2>Restricting access to components</h2>
534<p>Using an intent filter is not a secure way to prevent other apps from starting
535your components. Although intent filters restrict a component to respond to only
536certain kinds of implicit intents, another app can potentially start your app component
537by using an explicit intent if the developer determines your component names.
538If it's important that <em>only your own app</em> is able to start one of your components,
539set the <a href="{@docRoot}guide/topics/manifest/activity-element.html#exported">{@code
540exported}</a> attribute to {@code "false"} for that component.
541</p>
542</div>
543</div>
544
545<p>An implicit intent is tested against a filter by comparing the intent to each of the
546three elements. To be delivered to the component, the intent must pass all three tests.
547If it fails to match even one of them, the Android system won't deliver the intent to the
548component.  However, because a component may have multiple intent filters, an intent that does
549not pass through one of a component's filters might make it through on another filter.
550More information about how the system resolves intents is provided in the section below
551about <a href="#Resolution">Intent Resolution</a>.</p>
552
553<p class="caution"><strong>Caution:</strong> To avoid inadvertently running a different app's
554{@link android.app.Service}, always use an explicit intent to start your own service and do not
555declare intent filters for your service.</p>
556
557<p class="note"><strong>Note:</strong>
558For all activities, you must declare your intent filters in the manifest file.
559However, filters for broadcast receivers can be registered dynamically by calling
560{@link android.content.Context#registerReceiver(BroadcastReceiver, IntentFilter, String,
561Handler) registerReceiver()}. You can then unregister the receiver with {@link
562android.content.Context#unregisterReceiver unregisterReceiver()}. Doing so allows your app
563to listen for specific broadcasts during only a specified period of time while your app
564is running.</p>
565
566
567
568
569
570
571
572<h3 id="ExampleFilters">Example filters</h3>
573
574<p>To better understand some of the intent filter behaviors, look at the following snippet
575from the manifest file of a social-sharing app.</p>
576
577<pre>
578&lt;activity android:name="MainActivity">
579    &lt;!-- This activity is the main entry, should appear in app launcher -->
580    &lt;intent-filter>
581        &lt;action android:name="android.intent.action.MAIN" />
582        &lt;category android:name="android.intent.category.LAUNCHER" />
583    &lt;/intent-filter>
584&lt;/activity>
585
586&lt;activity android:name="ShareActivity">
587    &lt;!-- This activity handles "SEND" actions with text data -->
588    &lt;intent-filter&gt;
589        &lt;action android:name="android.intent.action.SEND"/>
590        &lt;category android:name="android.intent.category.DEFAULT"/>
591        &lt;data android:mimeType="text/plain"/>
592    &lt;/intent-filter&gt;
593    &lt;!-- This activity also handles "SEND" and "SEND_MULTIPLE" with media data -->
594    &lt;intent-filter&gt;
595        &lt;action android:name="android.intent.action.SEND"/>
596        &lt;action android:name="android.intent.action.SEND_MULTIPLE"/>
597        &lt;category android:name="android.intent.category.DEFAULT"/>
598        &lt;data android:mimeType="application/vnd.google.panorama360+jpg"/>
599        &lt;data android:mimeType="image/*"/>
600        &lt;data android:mimeType="video/*"/>
601    &lt;/intent-filter&gt;
602&lt;/activity&gt;
603</pre>
604
605<p>The first activity, {@code MainActivity}, is the app's main entry point&mdash;the activity that
606opens when the user initially launches the app with the launcher icon:</p>
607<ul>
608  <li>The {@link android.content.Intent#ACTION_MAIN} action
609  indicates this is the main entry point and does not expect any intent data.</li>
610  <li>The {@link android.content.Intent#CATEGORY_LAUNCHER} category indicates that this activity's
611  icon should be placed in the system's app launcher. If the <a
612  href="{@docRoot}guide/topics/manifest/activity-element.html">{@code &lt;activity>}</a> element
613  does not specify an icon with {@code icon}, then the system uses the icon from the <a
614  href="{@docRoot}guide/topics/manifest/application-element.html">{@code &lt;application>}</a>
615  element.</li>
616</ul>
617<p>These two must be paired together in order for the activity to appear in the app launcher.</p>
618
619<p>The second activity, {@code ShareActivity}, is intended to facilitate sharing text and media
620content. Although users might enter this activity by navigating to it from {@code MainActivity},
621they can also enter {@code ShareActivity} directly from another app that issues an implicit
622intent matching one of the two intent filters.</p>
623
624<p class="note"><strong>Note:</strong> The MIME type,
625<a href="https://developers.google.com/panorama/android/">{@code
626application/vnd.google.panorama360+jpg}</a>, is a special data type that specifies
627panoramic photos, which you can handle with the <a
628href="{@docRoot}reference/com/google/android/gms/panorama/package-summary.html">Google
629panorama</a> APIs.</p>
630
631
632
633
634
635
636
637
638
639
640
641
642
643<h2 id="PendingIntent">Using a Pending Intent</h2>
644
645<p>A {@link android.app.PendingIntent} object is a wrapper around an {@link
646android.content.Intent} object. The primary purpose of a {@link android.app.PendingIntent}
647is to grant permission to a foreign application
648to use the contained {@link android.content.Intent} as if it were executed from your
649app's own process.</p>
650
651<p>Major use cases for a pending intent include:</p>
652<ul>
653  <li>Declare an intent to be executed when the user performs an action with your <a
654  href="{@docRoot}guide/topics/ui/notifiers/notifications.html">Notification</a>
655  (the Android system's {@link android.app.NotificationManager}
656  executes the {@link android.content.Intent}).
657  <li>Declare an intent to be executed when the user performs an action with your
658  <a href="{@docRoot}guide/topics/appwidgets/index.html">App Widget</a>
659  (the Home screen app executes the {@link android.content.Intent}).
660  <li>Declare an intent to be executed at a specified time in the future (the Android
661  system's {@link android.app.AlarmManager} executes the {@link android.content.Intent}).
662</ul>
663
664<p>Because each {@link android.content.Intent} object is designed to be handled by a specific
665type of app component (either an {@link android.app.Activity}, a {@link android.app.Service}, or
666a {@link android.content.BroadcastReceiver}), so too must a {@link android.app.PendingIntent} be
667created with the same consideration. When using a pending intent, your app will not
668execute the intent with a call such as {@link android.content.Context#startActivity
669startActivity()}. You must instead declare the intended component type when you create the
670{@link android.app.PendingIntent} by calling the respective creator method:</p>
671
672<ul>
673  <li>{@link android.app.PendingIntent#getActivity PendingIntent.getActivity()} for an
674  {@link android.content.Intent} that starts an {@link android.app.Activity}.</li>
675  <li>{@link android.app.PendingIntent#getService PendingIntent.getService()} for an
676  {@link android.content.Intent} that starts a {@link android.app.Service}.</li>
677  <li>{@link android.app.PendingIntent#getBroadcast PendingIntent.getBroadcast()} for a
678  {@link android.content.Intent} that starts an {@link android.content.BroadcastReceiver}.</li>
679</ul>
680
681<p>Unless your app is <em>receiving</em> pending intents from other apps,
682the above methods to create a {@link android.app.PendingIntent} are the only
683{@link android.app.PendingIntent} methods you'll probably ever need.</p>
684
685<p>Each method takes the current app {@link android.content.Context}, the
686{@link android.content.Intent} you want to wrap, and one or more flags that specify
687how the intent should be used (such as whether the intent can be used more than once).</p>
688
689<p>More information about using pending intents is provided with the documentation for each
690of the respective use cases, such as in the <a
691href="{@docRoot}guide/topics/ui/notifiers/notifications.html">Notifications</a>
692and <a href="{@docRoot}guide/topics/appwidgets/index.html">App Widgets</a> API guides.</p>
693
694
695
696
697
698
699
700<h2 id="Resolution">Intent Resolution</h2>
701
702
703<p>When the system receives an implicit intent to start an activity, it searches for the
704best activity for the intent by comparing the intent to intent filters based on three aspects:</p>
705
706<ul>
707  <li>The intent action
708  <li>The intent data (both URI and data type)
709  <li>The intent category
710</ul>
711
712<p>The following sections describe how an intents are matched to the appropriate component(s)
713in terms of how the intent filter is declared in an app's manifest file.</p>
714
715
716<h3 id="ActionTest">Action test</h3>
717
718<p>To specify accepted intent actions, an intent filter can declare zero or more
719<a href="{@docRoot}guide/topics/manifest/action-element.html">{@code
720&lt;action&gt;}</a> elements.  For example:</p>
721
722<pre>
723&lt;intent-filter&gt;
724    &lt;action android:name="android.intent.action.EDIT" /&gt;
725    &lt;action android:name="android.intent.action.VIEW" /&gt;
726    ...
727&lt;/intent-filter&gt;
728</pre>
729
730<p>To get through this filter, the action specified in the {@link android.content.Intent}
731  must match one of the actions listed in the filter.</p>
732
733<p>If the filter does not list any actions, there is nothing for an
734intent to match, so all intents fail the test. However, if an {@link android.content.Intent}
735does not specify an action, it will pass the test (as long as the filter
736contains at least one action).</p>
737
738
739
740<h3 id="CategoryTest">Category test</h3>
741
742<p>To specify accepted intent categories, an intent filter can declare zero or more
743<a href="{@docRoot}guide/topics/manifest/category-element.html">{@code
744&lt;category&gt;}</a> elements.  For example:</p>
745
746<pre>
747&lt;intent-filter&gt;
748    &lt;category android:name="android.intent.category.DEFAULT" /&gt;
749    &lt;category android:name="android.intent.category.BROWSABLE" /&gt;
750    ...
751&lt;/intent-filter&gt;
752</pre>
753
754<p>For an intent to pass the category test, every category in the {@link android.content.Intent}
755must match a category in the filter. The reverse is not necessary&mdash;the intent filter may
756declare more categories than are specified in the {@link android.content.Intent} and the
757{@link android.content.Intent} will still pass. Therefore, an intent with no categories should
758always pass this test, regardless of what categories are declared in the filter.</p>
759
760<p class="note"><strong>Note:</strong>
761Android automatically applies the the {@link android.content.Intent#CATEGORY_DEFAULT} category
762to all implicit intents passed to {@link
763android.content.Context#startActivity startActivity()} and {@link
764android.app.Activity#startActivityForResult startActivityForResult()}.
765So if you want your activity to receive implicit intents, it must
766include a category for {@code "android.intent.category.DEFAULT"} in its intent filters (as
767shown in the previous {@code &lt;intent-filter>} example.</p>
768
769
770
771<h3 id="DataTest">Data test</h3>
772
773<p>To specify accepted intent data, an intent filter can declare zero or more
774<a href="{@docRoot}guide/topics/manifest/data-element.html">{@code
775&lt;data&gt;}</a> elements.  For example:</p>
776
777<pre>
778&lt;intent-filter&gt;
779    &lt;data android:mimeType="video/mpeg" android:scheme="http" ... /&gt;
780    &lt;data android:mimeType="audio/mpeg" android:scheme="http" ... /&gt;
781    ...
782&lt;/intent-filter&gt;
783</pre>
784
785<p>Each <code><a href="{@docRoot}guide/topics/manifest/data-element.html">&lt;data&gt;</a></code>
786element can specify a URI structure and a data type (MIME media type).  There are separate
787attributes &mdash; {@code scheme}, {@code host}, {@code port},
788and {@code path} &mdash; for each part of the URI:
789</p>
790
791<p style="margin-left: 2em">{@code &lt;scheme>://&lt;host>:&lt;port>/&lt;path>}</p>
792
793<p>
794For example:
795</p>
796
797<p style="margin-left: 2em">{@code content://com.example.project:200/folder/subfolder/etc}</p>
798
799<p>In this URI, the scheme is {@code content}, the host is {@code com.example.project},
800the port is {@code 200}, and the path is {@code folder/subfolder/etc}.
801</p>
802
803<p>Each of these attributes is optional in a <a
804href="{@docRoot}guide/topics/manifest/data-element.html">{@code &lt;data>}</a> element,
805but there are linear dependencies:</p>
806<ul>
807  <li>If a scheme is not specified, the host is ignored.</li>
808  <li>If a host is not specified, the port is ignored.</li>
809  <li>If both the scheme and host are not specified, the path is ignored.</li>
810</ul>
811
812<p>When the URI in an intent is compared to a URI specification in a filter,
813it's compared only to the parts of the URI included in the filter. For example:</p>
814<ul>
815  <li>If a filter specifies only a scheme, all URIs with that scheme match
816the filter.</li>
817  <li>If a filter specifies a scheme and an authority but no path, all URIs
818with the same scheme and authority pass the filter, regardless of their paths.</li>
819  <li>If a filter specifies a scheme, an authority, and a path, only URIs with the same scheme,
820authority, and path pass the filter.</li>
821</ul>
822
823<p class="note"><strong>Note:</strong> A path specification can
824contain a wildcard asterisk (*) to require only a partial match of the path name.</p>
825
826<p>The data test compares both the URI and the MIME type in the intent to a URI
827and MIME type specified in the filter.  The rules are as follows:
828</p>
829
830<ol type="a">
831<li>An intent that contains neither a URI nor a MIME type passes the
832test only if the filter does not specify any URIs or MIME types.</li>
833
834<li>An intent that contains a URI but no MIME type (neither explicit nor inferable from the
835URI) passes the test only if its URI matches the filter's URI format
836and the filter likewise does not specify a MIME type.</li>
837
838<li>An intent that contains a MIME type but not a URI passes the test
839only if the filter lists the same MIME type and does not specify a URI format.</li>
840
841<li>An intent that contains both a URI and a MIME type (either explicit or inferable from the
842URI) passes the MIME type part of the test only if that
843type matches a type listed in the filter.  It passes the URI part of the test
844either if its URI matches a URI in the filter or if it has a {@code content:}
845or {@code file:} URI and the filter does not specify a URI.  In other words,
846a component is presumed to support {@code content:} and {@code file:} data if
847its filter lists <em>only</em> a MIME type.</p></li>
848</ol>
849
850<p>
851This last rule, rule (d), reflects the expectation
852that components are able to get local data from a file or content provider.
853Therefore, their filters can list just a data type and do not need to explicitly
854name the {@code content:} and {@code file:} schemes.
855This is a typical case.  A <a
856href="{@docRoot}guide/topics/manifest/data-element.html">{@code &lt;data>}</a> element
857like the following, for example, tells Android that the component can get image data from a content
858provider and display it:
859</p>
860
861<pre>
862&lt;intent-filter&gt;
863    &lt;data android:mimeType="image/*" /&gt;
864    ...
865&lt;/intent-filter&gt;</pre>
866
867<p>
868Because most available data is dispensed by content providers, filters that
869specify a data type but not a URI are perhaps the most common.
870</p>
871
872<p>
873Another common configuration is filters with a scheme and a data type.  For
874example, a <a
875href="{@docRoot}guide/topics/manifest/data-element.html">{@code &lt;data>}</a>
876element like the following tells Android that
877the component can retrieve video data from the network in order to perform the action:
878</p>
879
880<pre>
881&lt;intent-filter&gt;
882    &lt;data android:scheme="http" android:type="video/*" /&gt;
883    ...
884&lt;/intent-filter&gt;</pre>
885
886
887
888<h3 id="imatch">Intent matching</h3>
889
890<p>Intents are matched against intent filters not only to discover a target
891component to activate, but also to discover something about the set of
892components on the device.  For example, the Home app populates the app launcher
893by finding all the  activities with intent filters that specify the
894{@link android.content.Intent#ACTION_MAIN} action and
895{@link android.content.Intent#CATEGORY_LAUNCHER} category.</p>
896
897<p>Your application can use intent matching in a similar way.
898The {@link android.content.pm.PackageManager} has a set of {@code query...()}
899methods that return all components that can accept a particular intent, and
900a similar series of {@code resolve...()} methods that determine the best
901component to respond to an intent.  For example,
902{@link android.content.pm.PackageManager#queryIntentActivities
903queryIntentActivities()} returns a list of all activities that can perform
904the intent passed as an argument, and {@link
905android.content.pm.PackageManager#queryIntentServices
906queryIntentServices()} returns a similar list of services.
907Neither method activates the components; they just list the ones that
908can respond.  There's a similar method,
909{@link android.content.pm.PackageManager#queryBroadcastReceivers
910queryBroadcastReceivers()}, for broadcast receivers.
911</p>
912
913
914
915
916