Overview and usage of Intent in Android

Source: Internet
Author: User

Overview and usage of Intent in Android

The Intent in Android is a very important and commonly used class. It can be used to start another component in the App or another component in the App, the components mentioned here refer to Activity, Service, and Broadcast.

Intent usage

Intent has the following important functions:
1. start Activity: You can pass the Intent object to the startActivity () method or startActivityForResult () method to start an Activity. The Intent object contains information about the Activity to be started and other necessary data.
2. start Service: You can pass the Intent object to the startService () method or bindService () method to start a Service. This Intent object contains information about the Service to be started and other necessary data. For more information about how to use startService () to start a Service, see the usage and Service lifecycle of startService in Android. For more information about how to use bindService () to start a Service, see bindService usage and Service lifecycle in Android.
3. Send broadcast: broadcast is a message that can be received by all apps. The Android system publishes various types of broadcasts, such as boot broadcast or mobile phone charging broadcast. We can also send broadcasts to other apps, and pass Intent objects to the sendBroadcast () method, sendOrderedBroadcast () method, or sendStickyBroadcast () method to send custom broadcasts.

Intent type

There are two types of Intent: explicit and implict.

Explicit Intent: If the Intent explicitly contains the complete Class Name (package name and class name) of the component to be started, the Intent is explicit. The most typical scenario for explicit Intent is to start a component in your App, because you must know the class name of the component to be started. For example, to respond to user operations, enable an Activity in your App or start a Service to download files through an explicit Intent.

Implicit Intent: If the Intent does not contain the complete Class Name of the component to be started, the Intent is implict, that is, implicit. Although the implicit Intent does not specify the Class Name of the component to be started, the implicit Intent usually specifies the action to be executed. Generally, the implicit Intent is used only when we want to start the component of another App in our App, let the component of another App receive and process the Intent. For example, if you want to display a location on a map, but your App does not support Map Display, you can put the location information into an Intent, then, specify the corresponding action for it, and use this implicit Intent to request other Map apps (such as Google Map and Baidu Map) to display a specified position in the Map. The implicit Intent also embodies a design philosophy of Android: my own apps do not need to cover all the features, and can be combined with other apps to provide users with a good user experience. The link between your App and other apps is implicit Intent.

When an explicit Intent is created to start Activity or Service, the system immediately starts the components specified in Intent.

When an implicit Intent is created for use, the Android system compares the information contained in the hidden Intent with the Intent Filters of the components registered in the manifest file in all other apps on the device, find the App that can receive and process the hidden Intent and corresponding components. If a component of multiple apps meets the conditions, a dialog box appears on Android asking users to select the App to start.

Intent Filter, which is an Intent Filter. A component can contain 0 or more Intent filters. Intent Filter is written in the manifest file of the App. It specifies the Intent type that the component can process and receive by setting the action or uri data type. If you set Intent Filter for your Activity, other apps may start your Activity by Using implicit Intent. If your Activity does not contain any Intent Filter, the Activity can only be started through an explicit Intent. Because we generally do not expose the complete Class Name of our component, in this case, other apps basically cannot start our Activity through Intent (because they do not know the full Class Name of the Activity), and it can only be started by our own App through explicit Intent.

To ensure App security, we should always use an explicit Intent to start the Service and do not set any Intent Filter for the Service. It is risky to start a Service by using an implicit Intent, because you are not sure which Service in the App will start to respond to your implicit Intent. what's even more sad, because the Service does not have the UI to run in the background, the user does not know which Service is running. Android 5.0 (API level 21) uses the implicit Intent to call the bindService () method. Android will throw an exception, but there are also related techniques, convert an implicit Intent to an explicit Intent, and then use an explicit Intent to call the bindService () method, for specific solutions, refer to the "Notes" section in "two-way communication between processes through Messenger and Service in Android", which contains solutions for relevant code.

Intent Composition

Android can search for the component to be started based on the information carried by Intent. Intent also carries some data information so that the component to be started can process the data in the Intent.

Intent consists of six parts: Component Name, Action, Data, Category, Extras, and Flags. Information can be used in three categories:
A. component Name, Action, Data, and Category are the types of components. The information in 4 determines which Component Android will start. Component Name is used in explicit Intent, action, Data, Category, Extras, and Flags are used in implicit Intent.
B. Extras is a type of data that contains the specific data information used for actual component processing.
C. Flags is a type of metadata that determines the actions Android performs on Intent.

Component name
Name of the component to be started. If you want to use an explicit Intent, you must specify this parameter. Once the component name is set, Android will directly pass the Intent to the component specified by the component name to start it. If the component name is not set, the Intent is implicit. The Android system uses other Intent information (such as the action, data, and category to be introduced below) make some comparisons to determine which component to start. Therefore, if you start a component in your App, you should specify the component name to start it through an explicit Intent (because you know the complete Class name of the component ).

Note that you should always specify the Component Name when starting the Service. Otherwise, you are not sure which component of the App is started, and the user cannot see which Service is started.

The field corresponding to component name in Intent is the ComponentName object. You can specify this value through the complete Class name of the component to be started (including the package name of the Application), such as com. example. exampleActivity. You can specify the component name by using the setComponent () method, setClass () method, setClassName () method, or Intent constructor.

Action
Is a string indicating the operation to be executed, such as viewing or selecting, which corresponds to the action tag in Intent Filter.

You can specify your own actions to facilitate the use of Intent in your App or call the components in your App through Intent in other apps. The Intent class and some other classes at the framework level in Android also provide many defined actions with certain general meanings. The following are common actions used to start an Activity:
Intent.ACTION_VIEWThe value is "android. intent. action. VIEW ". When you want to display some information to users through other activities, you can specify the Intent action as ACTION_VIEW. For example, you can VIEW an image in an image application, or you can display a location in a map application.
Intent.ACTION_SENDThe value is "android. intent. action. SEND. This action is often used for "sharing". When you want to share some data with other apps (such as QQ, Baidu cloud, etc, you can use this action to construct an Intent object and pass it to the startActivity () method. Because the Activity of multiple apps on the mobile phone can support ACTION_SEND, therefore, it is very likely that the following figure shows the situation for users to choose which App to share your data:

You can view the Intent class to learn more about some common Intent predefined actions. Some classes at the framework level in Android also define some actions, for example, some actions are defined in Settings to open different interfaces of the "set" application in the system to complete the specified configuration (such as WLAN Settings and language Settings ).

You can call the setAction () method of the intent object or specify the Intent action in the intent constructor.

If you define your own action, you must use the package name of your App as the prefix of the action. This is a good programming habit to avoid confusion. For example:

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

Data
The data in the Intent here refers to the MIME type of the Uri object and data, which corresponds to the data tag in the Intent Filter..
A complete Uri consists of scheme, host, port, and path. The format is :// : / For examplecontent://com.example.project:200/folder/subfolder/etc. A Uri is like a data link. A component can obtain the final data source based on this Uri. Generally, Uri and action are used in combination. For example, if we set action to ACTION_VIEW, we should provide the Uri of the document to be edited and modified.

When an Intent object is created, in addition to the specified Uri, the MIME type of the specified data is also very important. For example, an Activity can display images but cannot play a video. The Uri of the displayed image may be similar to the Uri of the video, to prevent Android from mistakenly passing an Intent object containing the video Uri to an Activity that can only display images, we need to specify the MIME type as an image in the Intent Filter of the Activity (for example) And set the corresponding image MIME for the Intent object, so that Android will pass the Intent to the qualified component based on the Uri and MIME types. Then there is a special case, if the Uri iscontent:This indicates that the data provided by the Uri comes from the local device, that is, the data is provided by the ContentProvider. In this case, Android will automatically deduce the MIME type based on the Uri, in this case, we do not need to specify the MIME type.

If you only set the data Uri, you need to call the setData () method of the Intent object; if you only set the MIME type of the data, you need to call the setType () method of the Intent object; to set the Uri and MIME types of data at the same time, call the setDataAndType () method of the Intent object.

If you want to set the Uri and MIME types of data at the same time, do not call the setData () method and setType () method of the Intent object successively because setData () methods and setType () are mutually exclusive. If the setData () method is called, the MIME type set by the setType () method in Intent is reset to null. If the setType () method is called, The Uri set by the setData () method in Intent is reset to null. Therefore, when you need to set both the data Uri and MIME types, you must call the setDataAndType () method of the Intent object instead of calling the setData () method and setType () method respectively.

Category
Category includes some other information about how the component processes the Intent. Although you can add any number of category to the Intent, most Intent actually does not need category.
The following are some common category:

CATEGORY_BROWSABLEThe target component allows itself to be started by a Web browser through a link, which may be an image link or e-mail information.

CATEGORY_LAUNCHERIdentifies an Activity as the entry Activity of an App.

You can find more predefined category in the Intent class.

Extras
Extras, as its name implies, is additional data information. A Bundle object in Intent stores various key-value pairs, the component that receives the Intent can read the required information from it to complete the corresponding work. Some Intent needs to carry data by Uri, and some Intent relies on extras to carry data information.

You can add additional data in the form of key-value pairs to Intent by calling the various overloaded putExtra (key, value) Methods of Intent objects. You can also directly create a Bundle object, pass in many key-value pairs to the Bundle object, and then set one of them to the Intent object by calling the putExtras (Bundle) method of the Intent object.

For example, if you create an Intent object whose action is ACTION_SEND and want to use it to start E-mail sending, you need to set two extra values for the Intent object:
UseIntent.EXTRA_EMAILSet the recipient as the key value and useIntent.EXTRA_SUBJECTSet the mail title as the key value.

The Intent class also specifies a number of pre-defined EXTRA _ * forms, such as (Intent.EXTRA_EMAILAndIntent.EXTRA_SUBJECT). If you want to declare your own extra, make sure that your App package name is your extra prefix, for example:

static final String EXTRA_GIGAWATTS = com.example.EXTRA_GIGAWATTS;

Flags
Flag indicates the meaning of the tag. The flag defined in the Intent class can act as the metadata of the Intent object. These flags will tell the Android system how to start the Activity (for example, the task of the newly started Activity) and how to treat the Activity after it is started (for example ). For more information, see the setFlags () method of Intent.

Explicit Intent usage example
Intent intent = new Intent(this, ActivityB.class);startActivity(intent);

The code above specifies in the Intent constructor that the ComponentName of the component to be started is ActivityB, and the intent object is explicit. When startActivity (intent) is called, the Android system immediately starts ActivityB.

Implicit Intent usage example

As mentioned earlier, when using implicit Intent, you must specify its action. If your App cannot complete a function, but other apps may complete the function, you can use the implicit Intent to start other apps to complete the corresponding function. For example, if you have a piece of text information and want to share it with other apps, the implicit Intent object starts a potentially shared App. The sample code is as follows:

Intent sendIntent = new Intent (); // sets action. action is very important for implicit Intent. setAction (Intent. ACTION_SEND); // set the MIME type of the data to sendIntent of the plain text type. setType (text/plain); // set additional data sendIntent. putExtra (Intent. EXTRA_TEXT, textMessage); // get PackageManager pm = getPackageManager (); // determine whether the system has any potential App Activity that supports receiving and processing the sendIntent if (pm. resolveActivity (sendIntent, 0 )! = Null) {startActivity (sendIntent );}

In the above Code, we have constructed an Intent object without setting the component name. Therefore, this Intent is an implicit Intent object. We first set the action value to intent. ACTION_SEND for Intent. action is very important for implicit Intent. Then we set the MIME type of intent data to the plain text type ("text/plain") to inform Android that our Intent has text data. Finally, we set the actual text data through the putExtra () method as additional data.
It should be noted that after the Intent object is built, the startActivity (sendIntent) method is not executed immediately, but the sendIntent is passed as a parameter to the resolveActivity () method of PackageManager, this method allows Android to find information about the potentially suitable startup component based on the sendIntent, and return the result in the form of a ResolveInfo object. If null is returned, it indicates that no component in the current system can receive and process the sendIntent. If the return value is not null, it indicates that at least one component in the system can receive and process the sendIntent. Only in this case can the code startActivity (sendIntent) be executed ), before starting a component through intent, it is a good programming habit to judge whether the component to be started does not exist, because if the system does not support your intent components, then when you call startActivity (), startService (), bindService (), and other methods, Android will throw an exception.

Force the user to use App Chooser

As mentioned above, if our Intent is implicit, when we try to start the component through startActivity (intent, the Android system may display the above file to ask which App the user wants to start. Sometimes the user sets an App as the default App, so that the Code startActivity (intent) will be executed next time) the App selection interface may not appear again, but directly run the application set as the default App last time. This is good for users to choose a default browser to open the web page, because a user is generally used to using a browser that he or she prefers.

But what if you don't want to use the same default App to handle this situation every time? At this time, we can clearly use the App selection dialog box in the Code. For example, when our App executes the sharing Function of ACTION_SEND, we want users to share their own data code, however, we are not sure which App the user wants to share it with. Every time we want to pop up the App selection dialog box, let the user decide which App to share it with. The sample code is as follows:

Intent sendIntent = new Intent (Intent. ACTION_SEND );... string title = select the App to share data. // verify whether an App can receive and process sendIntentif (sendIntent. resolveActivity (getPackageManager ())! = Null) {// create an intent object Intent chooserIntent = Intent that needs to be displayed in the App selection Dialog Box Based on sendIntent. createChooser (sendIntent, title); // we use chooserIntent as a parameter of the startActivity () method, rather than sendIntent startActivity (chooserIntent );}

First, we created the original sendIntent and set the action and other related information for it. Then we passed the sendIntent to the Intent. createChooser () method and created another chooserIntent. Next we call Intent. the resolveActivity (PackageManager) method determines whether an App in the system can receive and process sendIntent. This method is equivalent to the resolveActivity () method of PackageManager mentioned above. Finally, we use chooserIntent as the parameter of startActivity () method, instead of sendIntent. chooserIntent will force the Android system to display the interface on which the user selects the App to process Intent.

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.