SoFunction
Updated on 2025-03-11

Detailed explanation of Android Intent and IntentFilter cases

1. Preface

There are four major components in Android, and three of these components are related to Intent, which shows the status of Intent in the entire Android ecosystem. Intent is the carrier of information, and it can be used to request components to perform corresponding operations, but compared with this function, the structure of Intent itself is more worthy of our study.

2. Intent and components

Intent promotes interaction between components, which is very important to developers. It can also serve as a carrier of messages to guide components to perform corresponding behaviors. That is to say, Intent can carry data and pass it to Activity/Service/BroadcastReceiver.

  • Start Activity. Activity can be simply understood as a page in the mobile phone screen. You can start an instance of Activity by passing the Intent into the startActivity method, that is, a page. At the same time, the Intent can also carry data and pass it to the new Activity. If you want to get the newly created Activity execution result, you can start the Activity through the onActivityResult() method.
  • Start Service. Service is a background execution component that does not present interactive screens. You can start a service by tying an Intent into the startService() method to start a Service.
  • Pass the broadcast BroadCast. Broadcast is a message that any application can receive. By passing an Intent to the sendBroadcast(), sendOrderedBroadcast() or sendStickyBroadcast() methods, the broadcast can be passed to the receiver.

3. Intent type

In Android, Intent is divided into two types, explicit and implicit.

  • An explicit Intent can be found by class name, and an explicit Intent is used to start a component in the application, usually because we know the name of this component (Activity or Service). As shown in the following code, we know the name of the specific activity. To start a new activity, the following is the display Intent.
Intent intent = new Intent(context,);
startActivity(intent);
  • An implicit Intent does not specify a specific component, but it declares the operation to be performed, thus matching the corresponding component. The simplest operation of calling the system dialing page in Android is an implicit Intent.
Intent intent = new Intent(Intent.ACTION_DIAL);
Uri data = ("tel:" + "135xxxxxxxx");
(data);
startActivity(intent);

When using the display Intent to start the Activity or Service, the system will immediately start the specified component in the Intent object.

When using implicit Intent, the system finds the corresponding component to be started by comparing the IntentFilter in the Intent object with the IntentFilter that is dynamically declared in the component or code. If the IntentFilter of a component matches the IntentFilter in the Intent, the system will start the component and pass the Intent to it. If multiple components match at the same time, a selection box will pop up, allowing the user to choose which application to use to handle the Intent. For example, sometimes when clicking on a web page link, multiple applications will pop up, allowing the user to choose which browser to use to open the link. This is the case.

IntentFilter is usually defined in a file or can be set dynamically, usually used to declare which Intent component wants to accept. For example, if you set an IntentFilter for an Activity, you can start the Activity with a specific implicit Intent in the application or in other applications. If you do not set an IntentFilter for the Activity, you can only start the Activity by displaying the Intent.

Note that in order to ensure the stability of the system, the official recommends using display Intent to start the Service, and do not set an IntentFilter for the Service, because if you use implicit Intent to start the Service, we do not know that those services will respond to Intents, and since most services are invisible, we do not know that those services have been started, which is very dangerous. After Android 5.0 (API 21), if the bindService() method is called using an implicit Intent, the system will throw an exception.

4. Intent properties

As the carrier of the message, the system decides which specific component to start and passes the information needed during component execution according to it. The properties that an Intent can contain include Component, Action, Data, Category, Extras, and Flags. More detailed information about these properties can be viewed.here

  • Component, the name of the component to be started. This property is optional, but it is an important property of an explicit Intent. After setting this property, the Intent can only be passed to the components defined by the Component. An implicit Intent does not have this attribute. The system determines which component the Intent should be passed to based on other information (such as Action, Data, etc.). This property is the specific name of the target component (fully qualified class name), for example,. This property can be set through the constructor of setComonentName(), setClass(), setClassName() or Intent.
  • Action, indicates the string to perform the operation. It will affect the rest of the Intent information, such as Data, Extras. This property can be set through the setAction() method or the Intent constructor. Users can customize this property or use the Action value already available in the system. The following lists some common Action properties when starting an Activity.
    • ACTION_VIEW. When some information needs to be displayed, you can set the Intent Action to this value and call the startActivity() method.
    • ACTION_SEND. When the user has some information to share with other applications, you can set the Intent Action to this value and call the startActivity() method.
    • ACTION_DIAL, make a call, you can set the Intent Action to this value and call the startActivity() method
    • ACTION_EDIT, edit some files, you can set the Intent Action to this value, and call the startActivity() method
  • Data, it is a reference URI or a URI of data MIME type of data to be operated, and its value is usually associated with the Intent Action. For example, if the value of Action is set to ACTION_EDIT, the value of Data must contain the URI of the edited document. When we create an Intent, it is very important to set the MIME type. For example, an activity that can display pictures may not be able to play audio. The URI of pictures and audio is very similar. If we set the MIME type, it can help the system find the most suitable component to accept Intent. Sometimes, the MIME type can also be judged from the URI. For example, when Data is a URI containing a content: string, it can be clearly known that the data to be processed exists in the device and is controlled by the ContentProvider.
    • Use the setData() method to set the URI of the data reference, use the setType() method to set the MIME type of the data, and use the setDataAndType() method to set these two properties at the same time.
    • Note: If you want to set two properties, use the setDataAndType() method directly. Do not call the setData() and setType() methods at the same time, because the values ​​set by these two methods will overwrite each other.
    • public Intent setData(Uri data) {
      	mData = data;
      	mType = null;
      	return this;
      }
      public Intent setType(String type) {
          mData = null;
          mType = type;
          return this;
      }
      
  • Category, this property is a supplement to processing information of the Intent component. It is an ArraySet type container, so you can add any amount of supplementary information to it. At the same time, if this property is not set in Intent, it will not affect the parsed component information. This property can be set through the addCategory() method. The following lists some commonly used Category values.
    • CATEGORY_BROWSABLE. After setting Category to this value, when clicking on an image or link on the web page, the system will consider including this target activity in an optional list for users to choose to open an image or link.
    • CATEGORY_LAUNCHER, the initial activity of the application startup, this activity will be added to the system startup launcher.

The attributes of Intent (Component, Action, Data, Category) listed above can help the system determine specific components, but there are some Intent attributes that will not affect the determination of components.

  • Extras, in the form of key-value key-value pairs, stores the additional information needed by the component during the execution of operations. You can call the putExtra() method to set this property. This method accepts two parameters, one is key and the other is value. You can also add the instantiated Bundle to the Intent by instantiating a Bundle object that stores additional information and then calling the putExtras() method.
  • Flags, this property can indicate how the system starts an activity and how to handle it after startup. For example, which task is the Activity belong to (see Activity's four startup methods).

5. Explicit Intent Example

As mentioned above, an explicit Intent is an Intent used to start a specific component (Activity or Service). When creating an explicit Intent, you need to set the component name (Component) attribute, and other attributes are optional attributes.

// fileUrl is a URL string, such as "/"Intent downloadIntent = new Intent(context, );
((fileUrl));
startService(downloadIntent);

The constructor of the Intent here passes in two parameters, context and component name (Component). After calling the startService() method, the DownloadService service will be started in the current application.
Display the component name (Component) set in the Intent needs to be registered, so it is generally used to start the components in the current application.

6. Implicit Intent Example

Implicit Intent is more complicated than the displayed Intent. It can start components in the current application or components outside the current application. If the current application cannot handle the implicit Intent, but components in other applications can be processed, the system will pop up a box to let the user choose which component in which application to start.

For example, if the user has content that he wants to share with other applications, create an Intent, set its Action property to ACTION_SEND, then set the content to be shared into the Extras property, and then call the startActivity() method, and the user can choose which application to share the content to.

Note that if no application can handle the invisible Intent sent by the user, the calling component fails and the application may crash. Calling resolveActivity() method can confirm whether there is an Activity that can handle this Intent. If the return is non-empty, then at least one component can handle this Intent, and calling startActivity() is safe; if the return is null, it means that no component can handle this Intent, and this implicit Intent should not be used at this time.

// Share textMessage informationIntent sendIntent = new Intent();
(Intent.ACTION_SEND);
(Intent.EXTRA_TEXT, textMessage);
("text/plain");

// Confirm whether there is a component that can handle this implicit Intentif ((getPackageManager()) != null) {
    startActivity(sendIntent);
}

When calling startActivity() to pass an implicit Intent, the system will check all applications in the device to determine which applications can handle this implicit Intent (including the startActivity() operation and carry the text/plain type Intent). If only one application can handle this Intent, then directly evoke the application and pass the Intent to it; if multiple applications can handle this Intent, the system will pop up a selection box to let the user choose which application to call.

7. Forced to evoke the selection box

As mentioned above, if multiple applications can handle the same implicit Intent, the system will pop up the selection box, allowing the user to choose which application to call and set the application as the default opening method, and the selection box will not pop up in the future. It is very convenient if the user wants to use the user to handle this implicit Intent in the future (for example, if you open a web page, the user will usually prefer to use the same web browser).

However, if the user wants to use a different application to handle this implicit Intent every time, the selection box should pop up every time. The user can select the evoked application in the selection box, but the default opening method cannot be set. For example, when a user wants to share content to different applications based on their current location, a selection box will need to pop up each time.

The user needs to create an Intent through() and then call startActivity().

Intent sendIntent = new Intent(Intent.ACTION_SEND);
...

// Shared titleString title = getResources().getString(.chooser_title);
// Create an Intent that calls the selection boxIntent chooser = (sendIntent, title);

// Confirm whether there is an application that can handle this Intentif ((getPackageManager()) != null) {
    startActivity(chooser);
}

8. Accept implicit Intent

If you want to configure what implicit Intents your application can handle, you need to use the <intent-filter> tag in the file to set one or more filters for the component. Each filter specifies the Intent type that it can handle based on Action, Data, and Category. If the implicit Intent can match one of the filters set by the user, the system can evoke the corresponding component of the application and pass the Intent to the component.

The component should set up a separate processor for an operation it can handle. For example, the activity in the album may have two filters, one corresponding to the operation of browsing photos, and the other corresponding to the operation of editing photos. When this activity is started, it determines which operation to perform based on the information carried in the Intent.

Each filter is defined using the <intent-filter> tag and is nested in component tags, such as <activity> and <service> tags. In the <intent-filter> tag, the user can use one or more of the following three attributes to specify an acceptable Intent.

  • <action>, in this property, declares the actions that the component can perform. The value must be a string about the operation, not a class constant
  • <data>, use one or more data URIs (scheme, host, port, path, etc.) and the MIME type of the data to specify the accepted data type
  • <category>, declare the accepted Intent type

If the Activity component wants to accept an implicit Intent, it must have a filter with the <category> attribute CATEGORY_DEFAULT, because when the startActivity() and startActivityForResult() methods handle Intents, the default is that the accepting component has a filter with the <category> attribute CATEGORY_DEFAULT. If an Activity component does not declare such a filter, it cannot receive an implicit Intent.

For example, the following code declares an Activity component that can handle an implicit Intent of the action attribute ACTION_SEND and the data type is a text (text/plain).

<activity android:name="ShareActivity">
    <intent-filter>
        <action android:name=""/>
        <category android:name=""/>
        <data android:mimeType="text/plain"/>
    </intent-filter>
</activity>

Users can also create a filter containing multiple <action>, <data>, and <category> tags. When creating, you only need to make sure that the component can handle the filter-defined operations.

If multiple Intents are processed according to the combination of <action>, <data>, and <category> tags, then multiple filters need to be declared for this component.

The system will use these three attributes to compare the implicit Intent with the filters declared by all components. If all three attributes can match, the system will be able to pass this implicit Intent to this component, because if the components of multiple applications can match, a selection box will pop up, allowing the user to select an application to handle this implicit Intent.

In order to avoid accidentally starting other services, it is recommended to use the displayed Intent to start the service in the application, so that there is no need to declare filters for the Service in the file.

For Activity filters, they must be declared in the file, or they can be directly called by using the display Intent.

The filter declaration of the broadcast receiver can be declared in a file or can be dynamically registered using the registerReceiver() method. After use, dynamically log out using the unregisterReceiver() method.

9. Filter declaration example

The following filter statements can help you understand better.

&lt;activity android:name="MainActivity"&gt;
    &lt;!-- ShouldActivity是Should应用的启动入口页面,It will be stored in the systemlauncherIn the list --&gt;
    &lt;intent-filter&gt;
        &lt;action android:name="" /&gt;
        &lt;category android:name="" /&gt;
    &lt;/intent-filter&gt;
&lt;/activity&gt;

&lt;activity android:name="ShareActivity"&gt;
    &lt;!-- ShouldActivityAble to handleACTION_SENDBehavior and data typetext/plainImplicit ofIntent --&gt;
    &lt;intent-filter&gt;
        &lt;action android:name=""/&gt;
        &lt;category android:name=""/&gt;
        &lt;data android:mimeType="text/plain"/&gt;
    &lt;/intent-filter&gt;
    &lt;!-- ShouldActivityAble to handleACTION_SEND行为且数据类型是媒体内容Implicit ofIntent --&gt;
    &lt;intent-filter&gt;
        &lt;action android:name=""/&gt;
        &lt;action android:name=".SEND_MULTIPLE"/&gt;
        &lt;category android:name=""/&gt;
        &lt;data android:mimeType="image/*"/&gt;
        &lt;data android:mimeType="video/*"/&gt;
    &lt;/intent-filter&gt;
&lt;/activity&gt;

The first component named MainActivity is the application launch portal page. When the user clicks on the application icon, the activity will be started.

  • , indicating that the activity is the startup entrance of the application and does not require any data carried by the Intent.
  • , means to set the icon of the Activity as the application icon on the home screen of the phone. If it does not have an icon, use the icon of the Application.

The second component called ShareActivity can handle two implicit Intents and can accept sharing operations of text and media content. That is to say, if an implicit Intent can match any filter, the Activity can be evoked. Of course, it can also be started directly by displaying the Intent specification.

9. PendingIntent

PendingIntent is an encapsulation of Intent. Its main function is to let external applications execute internal intents, as if they are OK in your application.

Usually, PendingIntent is used in the following scenarios.

  • When the user clicks the notification bar, the Intent (Intent executed by the system's NotificationManager) is executed. For details, please refer tohere
  • When the user operates a widget suspended in the home screen, the Intent (the Intent executed by the home screen application) is executed. For details, please refer tohere
  • Intent executed at a certain time in the future (Intent executed by the system's AlarmManager)

Because each Intent object is instantiated for a specific component category (Activity/Service/BroadcastReceiver), when creating a PendingIntent, it should also be instantiated based on the same factors and instantiated the PendingIntent using the following method.

  • (), return a PendingIntent suitable for Activity components
  • (), return a PendingIntent suitable for Service components
  • (), return a PendingIntent for BroadcastReceiver

Of course, there are some other methods for obtaining PendingIntent objects, but the above three methods are used internally to obtain instantiated objects.

All three methods require the current application context, the encapsulated Intent, and one or more flags of how to use the Intent (for example, whether the Intent can be used multiple times).

The specific use of Pending is no longer expanded here. If you need to know the specific use, you can check it out.Use of PendingIntent in NotificationandUse of PendingIntent in the floating toolbar

10. Intent matching rules

As mentioned above, when an implicit Intent is sent, the system will match it with the filters of each component in the device. The matching attributes include Action, Category, and Data. These three attributes need to be matched successfully before the corresponding component can be evoked.

10.1 Action Matching Rules

A filter can either have an Action property or declare multiple Action properties. as follows:

<intent-filter>
    <action android:name="" />
    <action android:name="" />
    ...
</intent-filter>

The Action property in an implicit Intent can match the Action of a filter in the component (if a filter declares multiple Action properties, you only need to match one of them), then the match is successful.

If the filter does not declare the Action property, then only the implicit Intent without the Action property is set can match successfully.

10.2 Category matching rules

A filter can either declare Category attributes or multiple Category attributes, as follows:

<intent-filter>
    <category android:name="" />
    <category android:name="" />
    ...
</intent-filter>

All Category declared in an implicit Intent must be able to match the Category in a certain filter before the match is successful. For example, an implicit Intent with the Category property set to CATEGORY_BROWSABLE can also pass the above filter. That is to say, the content of the Category property of the filter must be greater than or equal to the Category property of the implicit Intent, and the implicit Intent can be matched successfully.

If an implicit Intent does not set the Category property, it can be matched by any filter's Category.

10.3 Data matching rules

A filter can either declare data attributes without declaring data attributes, as follows:

<intent-filter>
    <data android:mimeType="video/mpeg" android:scheme="http" ... />
    <data android:mimeType="audio/mpeg" android:scheme="http" ... />
    ...
</intent-filter>

Each Data attribute can specify the URI structure and data MIME type of the data. The URI includes four parts: scheme, host, port and path. Host and port are combined into the authority (host:port) part.

<scheme>://<host>:<port>/<path>

For example:

content://192.168.0.1:8080/folder/subfolder/etc

In this URI, the scheme is content, the host is 192.168.0.1, the port is 8080, and the path is folder/subfolder/etc. The network url we usually use is this format.

In a URI, each component is optional, but has linear dependencies

  • If there is no scheme part, the host part will be ignored
  • If there is no host part, the port part will be ignored
  • If there is no host part and port part, then the path part will be ignored

When performing URI matching, it is not a comparison of the whole thing, but a local comparison. The following are the URI matching rules.

  • If a URI declares only the scheme part, then all URIs with the same scheme will pass the match, and the other parts will not match.
  • If a URI declares the scheme part and the authority part, then the URI with the same scheme and authority as it can match successfully, and the path part does not match
  • If all parts of a URI are declared, only URIs with the same parts can match successfully

Note: The path part can be matched using wildcard characters (*), that is, part of the path.

When Data matches, both MIME type and URI will be matched, and the matching rules are as follows:

  • If the filter does not declare URI and MIME types, only invisible Intents without URI and MIME types can match successfully
  • If the URI is declared in the filter but the MIME type is not declared (the MIME type cannot be analyzed from the URI), then only the URI is the same as the filter URI and does not contain the IME type can match successfully
  • If the filter declares a MIME type but does not declare a URI, only an implicit Intent that contains the same MIME type but does not contain the URI can match successfully
  • If the filter declares the URI and MIME types (can be set directly or analyzed from the URI), only the implicit Intent containing the same URI and MIME types can match successfully

Note: When matching, you must match in units of filters, and you cannot match across filters. If a filter declares multiple Actions, Category, and Data, the Actions, Category, and Data contained in the implicit Intent can match the corresponding properties in the filter. That is to say, the properties declared in the filter are greater than or equal to the properties contained in the Intent, and the Intent can match successfully

11. Others

The system matches the Intent through filters and starts the corresponding components. It provides a series of query (queryIntentActivities()/queryIntentServices()/queryBroadcastReceivers()) methods to query components that can handle an Intent, and also provides a series of resolution (resolveActivity()/resolveService()) methods to determine the best startup component. These methods are very useful in some scenarios and can also help us reduce the risk of program crash.

12. Thinking

The above article explains Intent and IntentFilter in detail, most of them are system-level processing processes. But as an official already encapsulated information carrier, Intent can do a lot of things with it. For example, you can write your own set of matching rules. Intent is only used as a data carrier, and passes some information through it to realize the page jump logic of Fragment/Activity. Regarding the use of Intent, I believe there are more uses, and users need to explore step by step.

This is the introduction to this article about the detailed explanation of Android Intent and IntentFilter cases. For more related contents of Android Intent and IntentFilter, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!