Android Intent and Filter
Android Intent and Filter
An Android Intent is an abstract description of an operation to be performed. It can be used to start an activity via startActivity, send a broadcast to any interested broadcast receiver component via broadcastIntent, or communicate with a background service using startService(Intent) or bindService(Intent, ServiceConnection, int).
The Intent itself (an Intent object) is a passive data structure that stores the abstract description of the operation to be performed.
For example, you have an activity that needs to open the email client and send an email via the Android device. For this purpose, your activity needs to send an ACTION_SEND with an appropriate chooser to the Android intent handler. The specified chooser provides a suitable interface for the user to decide how to send their email data.
Intent email = new Intent(Intent.ACTION_SEND, Uri.parse("mailto:"));
email.putExtra(Intent.EXTRA_EMAIL, recipients);
email.putExtra(Intent.EXTRA_SUBJECT, subject.getText().toString());
email.putExtra(Intent.EXTRA_TEXT, body.getText().toString());
startActivity(Intent.createChooser(email, "Choose an email client from..."));
The syntax above calls the startActivity method to launch the email activity, and the code execution result looks like this:

For example, you have an activity that needs to open a URL in a browser on the Android device. For this purpose, your activity sends an ACTION_WEB_SEARCH intent to the Android intent handler to open the given URL in a browser. The intent handler parses a series of activities and selects the activity best suited for your intent, in this case, the web browser activity. The intent handler passes your web address to the web browser and opens the web browser activity.
String q = "https://www.runoob.com";
Intent intent = new Intent(Intent.ACTION_WEB_SEARCH );
intent.putExtra(SearchManager.QUERY, q);
startActivity(intent);
The example above searches for "www.runoob.com" on the Android search engine and provides keyword results on an activity.
Each component—activity, service, and broadcast receiver—has an independent mechanism for passing intents.
| Number | Methods and descriptions |
|---|---|
| 1 | Context.startActivity(): Intent passed to this method to start a new activity or make an existing activity do something new. |
| 2 | Context.startService(): Intent passed to this method to initialize a service or send new information to a continuously running service. |
| 3 | Context.sendBroadcast(): Intent passed to this method, and the information will be sent to all broadcast receivers interested in it. |
Intent object
An intent object is a package of information, similar to the information received by a component when the Android system receives it.
An intent object includes the following components, depending on what needs to be communicated or executed.
Action
This is a mandatory part of the intent object, represented as a string. In a broadcast intent, the action will be reported once it occurs. The action largely determines how other parts of the intent are organized. The Intent class defines a series of action constants corresponding to different intents. Here is a Standard Android Intent Actions list.
The action in the intent object can be set using the setAction() method and read using the getAction() method.
Data
Add data specifications to the intent filter. This specification can be just a data type (such as a metamodel attribute), a URI, or include both a data type and a URI. The URI is specified by attributes of different parts.
These attributes specifying the URL format are optional, but they are also independent -
- If the intent filter does not specify a pattern, all other URI attributes will be ignored.
- If no host is specified for the filter, the port attribute and all path attributes will be ignored.
The setData() method can only specify data using a URI, setType() can only specify data using a metadata type, and setDataAndType() can specify both a URI and a metadata type. The URI is read via getData(), and the type is read via getType().
The following are some examples of actions/data groups -
| Sequence number | Action/Data group and description |
|---|---|
| 1 | ACTION_VIEW content://contacts/people/1: Displays information for the user with ID 1. |
| 2 | ACTION_DIAL content://contacts/people/1: Display the phone dialer and populate with user 1's data. |
| 3 | ACTION_VIEW tel:123: Display the phone dialer and populate with the given number. |
| 4 | ACTION_DIAL tel:123: Display the phone dialer and populate with the given number. |
| 5 | ACTION_EDIT content://contacts/people/1: Edit the information for the user with ID 1. |
| 6 | ACTION_VIEW content://contacts/people/: Displays the user list for viewing. |
| 7 | ACTION_SET_WALLPAPER: Displays the wallpaper selection settings. |
| 8 | ACTION_SYNC: Synchronizes data, the default value is: android.intent.action.SYNC |
| 9 | ACTION_SYSTEM_TUTORIAL: Enables the platform-defined tutorial (default tutorial or startup tutorial) |
| 10 | ACTION_TIMEZONE_CHANGED: Notification when the timezone is changed |
| 11 | ACTION_UNINSTALL_PACKAGE: Runs the default uninstaller |
Category
A category is an optional part of the intent, a string that contains additional information about the intents that a component of this type needs to handle. The addCategory() method adds a category to the intent object, the removeCategory() method removes a previously added category, and getCategories() retrieves all categories set in the intent object. Here is a Standard Android Intent Categories list.
You can see the intent filters in the following section to understand how we use categories to select the appropriate activity based on the corresponding intent.
Extra data
This is additional information described as key-value pairs passed to the component that needs to handle the intent. It is set using the putExtras() method and read using the getExtras() method. Here is a Standard Android Intent Extras list.
Flags
These flags are optional parts of the intent, describing how the Android system should launch the activity and how it should be handled after launching.
| Index | Tag and Description |
|---|---|
| 1 | FLAG_ACTIVITY_CLEAR_TASK: If set in the intent and passed via Context.startActivity, this flag will clear all existing tasks associated with the activity before the activity starts. The activity will become the root of an empty task, and all old activities will be terminated. This flag can be used in combination with FLAG_ACTIVITY_NEW_TASK. |
| 2 | FLAG_ACTIVITY_CLEAR_TOP: If this flag is set, the activity will be launched in the current running task. This does not start a new activity instance; all activities on top of it will be closed, and this intent will be passed to the existing (currently at the top) activity as a new intent. |
| 3 | FLAG_ACTIVITY_NEW_TASK: This flag is generally used to make the activity behave in a "launcher" style: providing the user with data that can be completed independently and starting a completely independent activity. |
Component name
The component name object is an optional domain representing an Activity, Service, or BroadcastReceiver class. If set, the intent object is passed to an instance of the class designed in the implementation; otherwise, Android uses other information in the intent to locate a suitable target. The component name can be set using setComponent(), setClass(), or setClassName(), and retrieved using getComponent().
Intent type
Android supports two types of intents.

Explicit intent
Explicit intent is used to connect the internal world of an application. Assuming you need to connect one Activity to another, we can do this by displaying an intent. The figure below shows connecting the first Activity to the second Activity by clicking a button.

These intents specify the target component by name, generally used for internal application information—for example, one Activity starting a subordinate Activity or starting a sibling Activity. For example:
Original prompt (Chinese, left untranslated)
// 通过指定类名的显式意图
Intent i = new Intent(FirstActivity.this, SecondAcitivity.class);
// Start target activity
startActivity(i);
Implicit intent
These intents are not named for the target, and the domain of the component name is empty. Implicit intents are often used to activate components of other applications. For example:
Intent read1=new Intent();
read1.setAction(android.content.Intent.ACTION_VIEW);
read1.setData(ContactsContract.Contacts.CONTENT_URI);
startActivity(read1);
The code above will produce the following result:

The target component receives the intent and can use the getExtras() method to retrieve additional data sent by the source component. For example:
Original prompt (Chinese, left untranslated)
// 在代码中的合适位置获取包对象
Bundle extras = getIntent().getExtras();
// Decompress data by key
String value1 = extras.getString("Key1");
String value2 = extras.getString("Key2");
Instance
The instance below demonstrates using Android intents to launch the functions of various built-in Android applications.
| Steps | Description |
|---|---|
| 1 | Create an Android application using Android Studio IDE and name it Intent filter, with the package name com.runoob.intentfilter. When creating the project, ensure that the target SDK and compilation use the latest version of the Android SDK and advanced APIs. |
| 2 | Modify the src/com.runoob.intentfilter/MainActivity.java file and add code to define two listeners corresponding to the "Launch Browser" and "Launch Phone" buttons. |
| 3 | Modify the res/layout/activity_main.xml layout file and add 3 buttons in the linear layout. |
| 4 | Start the Android emulator to run the application and verify the results of the changes made to the application. |
The content of the src/com.runoob.intentfilter/MainActivity.java file is as follows:
package com.runoob.intentfilter;
import android.content.Intent;
import android.net.Uri;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
public class MainActivity extends ActionBarActivity {
Button b1,b2;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
b1=(Button)findViewById(R.id.button);
b1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent i = new Intent(android.content.Intent.ACTION_VIEW, Uri.parse("https://www.runoob.com"));
startActivity(i);
}
});
b2=(Button)findViewById(R.id.button2);
b2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent i = new Intent(android.content.Intent.ACTION_VIEW,Uri.parse("tel:9510300000"));
startActivity(i);
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
Below is the content of res/layout/activity_main.xml:
Original prompt (Chinese, left untranslated)
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin"
tools:context=".MainActivity">
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Intent instance"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:textSize="30dp" />
<TextView
android:id="@+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="www.runoob.com"
android:textColor="#ff87ff09"
android:textSize="30dp"
android:layout_below="@+id/textView1"
android:layout_centerHorizontal="true" />
<ImageButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/imageButton"
android:src="@drawable/ic_launcher"
android:layout_below="@+id/textView2"
android:layout_centerHorizontal="true" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/editText"
android:layout_below="@+id/imageButton"
android:layout_alignRight="@+id/imageButton"
android:layout_alignEnd="@+id/imageButton" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Launch browser"
android:id="@+id/button"
android:layout_alignTop="@+id/editText"
android:layout_alignRight="@+id/textView1"
android:layout_alignEnd="@+id/textView1"
android:layout_alignLeft="@+id/imageButton"
android:layout_alignStart="@+id/imageButton" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Make a call"
android:id="@+id/button2"
android:layout_below="@+id/button"
android:layout_alignLeft="@+id/button"
android:layout_alignStart="@+id/button"
android:layout_alignRight="@+id/textView2"
android:layout_alignEnd="@+id/textView2" />
</RelativeLayout>
Below is the content of res/values/strings.xml, defining two new constants.
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">Intent filter</string>
<string name="action_settings">Settings</string>
</resources>
Below is the default content of AndroidManifest.xml:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.runoob.intentfilter"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="22" />
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/Base.Theme.AppCompat" >
<activity
android:name="com.runoob.intentfilter.MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Let's run the application with the recently modified Intent filter. I assume you have already created an AVD during the installation environment setup. Open the activity file in your project and click the icon in the toolbar to run the application in Android Studio. Android Studio installs and launches the application on the AVD. If everything goes well, it will display as follows in the emulator window:
Now click the "Launch Browser" button, which will launch a browser based on the configuration and display https://www.runoob.com:

Similarly, you can click the "Launch Phone" button to open the phone interface, which will allow you to dial the given phone number.

Intent filter
Intent Filter
You have seen how to use intents to invoke other activities. The Android operating system uses filters to specify a set of activities, services, and broadcast receivers that handle intents, which rely on the actions, categories, and data patterns specified in the intent. Use the
The following example shows a part of the AndroidManifest.xml file, specifying that an activity com.runoob.intentfilter.CustomActivity can be invoked by the set of actions, categories, and data.
<activity android:name=".CustomActivity"
android:label="@string/app_name">
<intent-filter>
<action android:name="android.intent.action.VIEW" />
<action android:name="com.example.MyApplication.LAUNCH" />
<category android:name="android.intent.category.DEFAULT" />
<data android:scheme="http" />
</intent-filter>
</activity>
When an activity is defined by the filter above, other activities can invoke this activity in the following way. Use android.intent.action.VIEW, use the com.runoob.intentfilter.LAUNCH action, and provide the android.intent.category.DEFAULT category.
The element specifies the data type expected by the activity to be invoked. In the example above, the data expected by the custom activity starts with "http://".
There are cases where, through a filter, the intent will be passed to multiple activities or services, and the user will be asked to start which component. If the target component is not found, an exception will occur.
Before invoking an activity, there is a series of Android checks:
- Filter
One or more actions must be listed and cannot be empty; the filter must contain at least one element. If multiple actions are mentioned, Android attempts to match one of the mentioned actions before invoking the activity. - Filter
May list 0, 1, or more categories. If no categories are mentioned, Android passes this test. If multiple categories are mentioned, the intent passes the type test, and the classification of each intent object must match one of the classifications in the filter. - Eachelement can specify a URI and a data type (MIME type). There are independent attributes for each part of the URI, such as scheme, host, port, and path. The intent contains a URI and a type, and it passes the data type test only if its type matches one of the types listed in the filter.
Instance
The following instances are modifications of the above instances. Here we will see how Android resolves conflicts if an intent calls two defined activities; how to use filters to call custom activities; and that an exception occurs if no suitable activity is defined for the intent.
| Steps | Description |
|---|---|
| 1 | Create an Android application using Android Studio IDE and name it Intent filter, with the package name com.runoob.intentfilter. When creating the project, ensure that the target SDK and compilation use the latest version of the Android SDK to use advanced APIs. |
| 2 | Modify the src/com.runoob.intentfilter/MainActivity.java file to add code to define three listeners corresponding to the three buttons defined in the layout file. |
| 3 | Add the src/com.runoob.intentfilter/CustomActivity.java file to include an activity that can be called by different intents. |
| 4 | Modify the res/layout/activity_main.xml file to add three buttons in the linear layout. |
| 5 | Add the res/lauout/custom_view.xml layout file to simply |
| 6 | Modify the AndroidManifest.xml file to add |
| 7 | Start the Android emulator to run the application and verify the results of the changes made to the application. |
The content of src/com.runoob.intentfilter/MainActivity.java is as follows:
package com.runoob.intentfilter;
import android.content.Intent;
import android.net.Uri;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
public class MainActivity extends ActionBarActivity {
Button b1,b2,b3;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
b1=(Button)findViewById(R.id.button);
b1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent i = new Intent(android.content.Intent.ACTION_VIEW,Uri.parse("https://www.runoob.com"));
startActivity(i);
}
});
b2=(Button)findViewById(R.id.button2);
b2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent i = new Intent("com.runoob.intentfilter.LAUNCH",Uri.parse("https://www.runoob.com"));
startActivity(i);
}
});
b3=(Button)findViewById(R.id.button3);
b3.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent i = new Intent("com.runoob.intentfilter.LAUNCH",Uri.parse("https://www.runoob.com"));
startActivity(i);
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
The content of src/com.runoob.intentfilter/CustomActivity.java is as follows:
package com.runoob.intentfilter;
import android.app.Activity;
import android.net.Uri;
import android.os.Bundle;
import android.widget.TextView;
public class CustomActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.custom_view);
TextView label = (TextView) findViewById(R.id.show_data);
Uri url = getIntent().getData();
label.setText(url.toString());
}
}
The content of res/layout/activity_main.xml is as follows:
Original prompt (Chinese, left untranslated)
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin"
tools:context=".MainActivity">
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Intent instance"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:textSize="30dp" />
<TextView
android:id="@+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="www.runoob.com"
android:textColor="#ff87ff09"
android:textSize="30dp"
android:layout_below="@+id/textView1"
android:layout_centerHorizontal="true" />
<ImageButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/imageButton"
android:src="@drawable/ic_launcher"
android:layout_below="@+id/textView2"
android:layout_centerHorizontal="true" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/editText"
android:layout_below="@+id/imageButton"
android:layout_alignRight="@+id/imageButton"
android:layout_alignEnd="@+id/imageButton" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Launch browser via the View action"
android:id="@+id/button"
android:layout_alignTop="@+id/editText"
android:layout_alignRight="@+id/textView1"
android:layout_alignEnd="@+id/textView1"
android:layout_alignLeft="@+id/imageButton"
android:layout_alignStart="@+id/imageButton" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Launch browser via the Launch action"
android:id="@+id/button2"
android:layout_below="@+id/button"
android:layout_alignLeft="@+id/button"
android:layout_alignStart="@+id/button"
android:layout_alignRight="@+id/textView2"
android:layout_alignEnd="@+id/textView2" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Exception"
android:id="@+id/button3"
android:layout_below="@+id/button2"
android:layout_alignLeft="@+id/button2"
android:layout_alignStart="@+id/button2"
android:layout_alignRight="@+id/textView2"
android:layout_alignEnd="@+id/textView2" />
</RelativeLayout>
The content of res/layout/custom_view.xml is as follows:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<TextView android:id="@+id/show_data"
android:layout_width="fill_parent"
android:layout_height="400dp"/>
</LinearLayout>
The content of res/values/strings.xml is as follows:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">My Application</string>
<string name="action_settings">Settings</string>
</resources>
The content of AndroidManifest.xml is as follows:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.runoob.intentfilter"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="22" />
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/Base.Theme.AppCompat" >
<activity
android:name="com.runoob.intentfilter.MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name="com.runoob.intentfilter.CustomActivity"
android:label="@string/app_name">
<intent-filter>
<action android:name="android.intent.action.VIEW" />
<action android:name="com.runoob.intentfilter.LAUNCH" />
<category android:name="android.intent.category.DEFAULT" />
<data android:scheme="http" />
</intent-filter>
</activity>
</application>
</manifest>
Let's run the modified Intent filter application. I assume you have created an AVD during the installation environment setup. Open the active file in your project and click the icon in the toolbar to run the application in Android Studio. Android Studio installs and launches the application on the AVD. If everything goes well, it will display as follows in the emulator window:
Click the first button "Launch browser with View action". Here we define our custom activity to include "android.intent.action.VIEW", and the Android system has defined a default activity corresponding to the VIEW action to launch the web browser, so Android displays the following options to choose which activity to launch:

If you select the browser, Android will launch the web browser and open the www.runoob.com website. If you select the IntentDemo option, Android will launch CustomActivity, which does nothing, merely capturing and displaying the passed data in a TextView.

Now, return using the back button and click the "Launch browser with Launch action" button. Here, the Android application filter selects the defined activity and simply launches the custom activity.

Return again using the back button and click the "Exception condition" button. Here, Android tries to find a valid filter provided by the intent, but no defined valid activity is found. Because we used data with https instead of http and provided the correct action, Android throws an exception. As follows:
image
