Android Intents and Intent Filters Example tutorials

Android Intents and Intent Filters Example tutorials

Intent is a messaging object you can use to request an action from another app component. Even though intents facilitate communication between components in many ways, there are three basic use-cases:

To initiate an activity

An Activity stands for a unitary screen in an app. You can begin a new instance of an Activity by passing Intent to startActivity (). The Intent describes the movement to start and carries any necessary data. If you want to receive a result from the activity when it finishes, call startActivityForResult (). Your activity receives the result as a break up Intent object in your activity’s onActivityResult() callback.

To start a service

A Service is a component that performs operations in the background without a user interface. You can start a service to perform a one-time operation (such as download a file) by passing an Intent to startService(). The Intent describes the service to start and carries any necessary data. If the service is designed with a client-server interface, you can unite to the service from another section by passing an Intent to bindService().

 To deliver a broadcast

A broadcast is a message that  can be received by any app. The system delivers different broadcasts for system events, like when the system boots up or the device begins charging. You can deliver a broadcast to other apps by passing an Intent to sendBroadcast (), sendOrderedBroadcast(), or sendStickyBroadcast().

Intent Types

Intents are of two types

Explicit intents

This spells out the constituent to begin by name- the fully-qualified class name. You’ll characteristically make use of an explicit intent to begin a constituent in your own app, due to the fact that you know the class name of the activity or service you want to initiate. For instance, begin a new activity in response to a user action or begin a service to download a file in the backdrop.

 Implicit intents

They do not name a particular constituent, but rather declare a general action to carry out, which permits a constituent from another app to take it. For instance, if you want to illustrate to the user a location on a map, you can make use of an implicit intent to request that another able app show a particular location on a map. When you produce an explicit intent to start an activity or service, the system instantly begins the app constituent specified in the Intent object.

The figure above illustrates the way an implicit intent is delivered via the system to kick another activity: [1] Activity A produces an Intent with an action explanation and passes it to start Activity(). [2] The Android System searches all apps for an intent filter that matches the intent. When a match is discovered, [3] the system begins the matching activity (Activity B) by calling upon its onCreate () technique and passing it to the Intent.

When you produce an implicit intent, the Android system discovers the suitable constituent to begin by comparing the contents of the intent to the intent filters affirmed in the manifest file of other apps on the device. If the intent matches an intent filter, the system begins that constituent and distributes it the Intent object. If multiple intent filters are well-matched, the system displays a dialog so the user can pick which app to make use of.

An intent filter is an appearance in an app’s apparent file that specifies the type of intents that the constituent would like to accept. For occurrence, by declaring an intent filter for an activity, you make it possible for other apps to frankly begin your activity with a particular kind of intent. Similarly, if you do not state any intent filters for an activity, then it can be started only with an explicit intent.

To make sure your app is secure, constantly make use of an explicit intent when initiating a Service and do not assert intent filters for your services. Making use of an implicit intent to kick-start a service is a security hazard due to the fact that you cannot be sure what service will respond to the intent, and the user cannot visualize which service begins. Starting with Android 5.0 (API level 21), the system throws an exemption if you call bindService () with an inherent intent.

Building an Intent

An Intent object bears information that the Android system makes to establish which constituent to begin like the exact constituent  name or constituent category that ought to receive the intent, together with information that the recipient constituent makes use in order to correctly carry out the action (like the action to take and the data to act upon).

The primary information contained in an Intent is the following:

Component name

The name of the constituent to star is optional, but it’s the unsafe piece of information that makes intent explicit, meaning that the intent ought to be delivered only to the app constituent defined by the constituent name. Without a constituent name, the intent is implicit and the system decides which constituent ought to receive the intent based on the other intent information like the action, data, and category—explained below. So if you require initiating a particular constituent in your app, you ought to spell out the constituent name.

When initiating a Service, you ought to constantly specify the constituent name. Otherwise, you cannot be sure what service will act in response to the intent, and the user cannot see which service begins.

This field of the Intent is a ComponentName object, which you can spell out with the use of a fully qualified class name of the target constituent, which includes package name of the app. For instance com.example.ExampleActivity. You can set the constituent name with setComponent(), setClass(), setClassName(), or with the Intent constructor.

Action

This is a string that identifies the generic action to carry out (like view or pick). In the case of a broadcast intent, this is the action that occurred and is being reported. The action basically determines how the rest of the intent is planned—chiefly what is contained in the data and extras.

You can spell out your own actions for use by intents within your app (or for use by other apps to call upon constituents in your app, but you ought to typically use action constants defined by the Intent class or other framework classes. Below are a few common actions for starting an activity:

ACTION_VIEW

Use this action in an intent with startActivity() when you have a few information that an activity can specify to the user, like a photo to view in a gallery app, or an address to view in a map app.

ACTION_SEND

This is as well known as the “share” intent, you ought to make use of this in an intent with startActivity() when you have a few data that the user can illustrate via a different app, like an email app or social sharing app.

View the Intent class reference for more constants that define generic actions. Other actions are defined somewhere else in the Android framework, like in Settings for actions that open particular screens in the system’s Settings app.

You can spell out the action for an intent with setAction() or with an Intent constructor.

If you characterize your own actions, be sure to include your app’s package name as a prefix. For instance:

static final String ACTION_TIMETRAVEL = “com.example.action.TIMETRAVEL”;

Data

The URI (a Uri object) that references the data to be acted on and/or the MIME type of that data. The type of data supplied is usually dictated by the intent’s action. For example, if the action is ACTION_EDIT, the data supposed to contain the URI of the document to edit.

When producing intent, it’s often significant to spell out the type of data (its MIME type) in addition to its URI. For instance, an activity that’s capable of exhibiting images possibly won’t be capable of playing an audio file, even though the URI formats could be related. So spell out the MIME type of your data performs the Android system discovers the best constituent to receive your intent.

All the same, the MIME type can sometimes be inferred from the URI—typically when the data is content: URI, which illustrates the data is situated on the device and controlled by a ContentProvider, which makes the data MIME category visible to the system.

To place only the data URI, call setData (). To set only the MIME group, call set Type (). If required, you can set equally explicitly with setDataAndType().

If you want to set both the URI and MIME type, do not call setData() and setType() because they each nullify the value of the other. Always use setDataAndType () to set both URI and MIME type.

Category

A string containing extra information about the type of constituent that ought to take care of the intent. Any number of group descriptions can be placed in intent, but the majority of intents do not require a category. Here are a few common categories:

CATEGORY_BROWSABLE

The target activity permits itself to be started by a web browser to display data referenced by a link—such as an image or an e-mail message.

CATEGORY_LAUNCHER

The activity is the initial activity of a task and is listed in the system’s application launcher. You can specify a category with addCategory ().

These properties listed above (component name, action, data, and category) stand for the defining characteristics of intent. By reading these properties, the Android system is able to determine which app constituent it ought to start.

However, intent can carry extra information that does not affect how it is resolved to an app constituent. An intent can as well supply:

Extras

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

You can add extra data with various put Extra () methods, each accepting two parameters: the key name and the value. You can also create a Bundle object with all the extra data, then insert the Bundle in the Intent with putExtras().

For example, when creating an intent to send an email with ACTION_SEND, you can specify the “to” recipient with the EXTRA_EMAIL key, and specify the “subject” with the EXTRA_SUBJECT key.

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

static final String EXTRA_GIGAWATTS = “com.example.EXTRA_GIGAWATTS”;

Flags

Flags defined in the Intent class that function as metadata for the intent. The flags may instruct the Android system how to launch an activity (for example, which task the activity should belong to) and how to treat it after it’s launched (for example, whether it belongs in the list of recent activities).

For more information, see the setFlags () method.

Example explicit intent

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

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

// Executed in an Activity, so ‘this’ is the Context
// The fileUrl is a string URL, such as “http://www.example.com/image.png”
Intent downloadIntent = new Intent(this, DownloadService.class);
downloadIntent.setData(Uri.parse(fileUrl));
startService(downloadIntent);

The Intent(Context, Class) constructor supplies the app Context and the constituent a Class object. As such, this intent explicitly begins the DownloadService class in the app.

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

Example of implicit intent

An implicit intent spell out an action that can call upon any app on the device able to carry out the action. Making use of an implicit intent is helpful when your app cannot carry out the action, but other apps almost certainly can and you’d like the user to select which app to use.

For instance, if you have content you want the user to share with other people, create intent with the ACTION_SEND action and add extras that spell out the content to share. When you call startActivity () with that intent, the user can choose an app through which to share the content.

It’s likely that a user won’t have any apps that handle the implicit intent you send to startActivity(). If that occurs, the call will fail and your app will collapse. To check that an activity will receive the intent, call resolve Activity () on your Intent object. If the result is non-null, then there is at least one app that can handle the intent and it’s safe to call startActivity (). If the result is unacceptable, you ought not to use the intent and, if possible, you ought to disable the feature that issues the intent.

// Create the text message with a string
Intent sendIntent = new Intent();
sendIntent.setAction(Intent.ACTION_SEND);
sendIntent.putExtra(Intent.EXTRA_TEXT, textMessage);
sendIntent.setType(HTTP.PLAIN_TEXT_TYPE); // "text/plain" MIME type

// Verify that the intent will resolve to an activity
if (sendIntent.resolveActivity(getPackageManager()) != null) {
    startActivity(sendIntent);
}

OTHER INTERESTING POSTS:

Add a Comment