Intent overview and use of Android

Source: Internet
Author: User

Intent in Android is a very important and commonly used class that can be used to launch another component of the app in one component or a component that launches another app, which refers to activity, service, and broadcast.

Use of intent

Intent mainly has the following important uses:
1. Start activity: You can pass the intent object to the StartActivity () method or the Startactivityforresult () method to start an activity, The intent object contains information about the activity to start and other necessary data.
2. Start Service: You can pass the intent object to the StartService () method or the Bindservice () method to start a service that contains information about the service to start and other necessary data. For starting a service using the StartService () method, see the blog post, "StartService usage and service life cycle" in Android. For starting a service using the Bindservice () method, see the blog post, "Bindservice usage and service life cycle" in Android.
3. Send a broadcast: A broadcast is a message that all apps can receive. The Android system publishes various types of broadcasts, such as post-launch broadcasts or mobile phone charging broadcasts. We can also send broadcasts to other apps, and you can pass the intent object to the Sendbroadcast () method or the Sendorderedbroadcast () method or the Sendstickybroadcast () method to send a custom broadcast.

Types of Intent

There are two types of intent:explicit (Explicit) and implict (implicit).

Explicit Intent: If intent explicitly contains the complete class name (package name and class name) of the component to be started, then this intent is explict, that is, explicit. The most typical scenario for using explicit intent is to launch a component in your own app, because you must know your own class name for the component you want to start. For example, in response to user actions, an explicit intent launches an activity in your app or launches a service download file.

Implicit Intent: If intent does not contain the full class name of the component to be started, then this 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 typically specifies the action to be executed. In general, the implicit intent is used only when we want to launch another app's component in our app via intent, and let another app's component receive and process the intent. For example, if you want to show a location to a user on a map, but your app doesn't support a map display, you can put the location information into a intent and then assign it a corresponding action to request other map-based apps through an implicit intent such as Google Map, Baidu maps, etc.) to show a specific location in the map. The implicit intent also embodies the design philosophy of Android: My own app doesn't need to be all-encompassing, and can be combined with other apps to give users a great user experience. The link between your app and other apps is an implicit intent.

When an explicit intent is created to start the activity or service, the component specified in intent is immediately started.

When an implicit intent is created, the Android system compares the information contained in the implicit intent with the intent filters of the components registered in manifest files in all other apps on the device, Find the app and the corresponding component that can receive processing the implicit intent. If a component in multiple apps meets the criteria, Android pops up a dialog box that lets the user choose which app to launch.

Intent filter, or Intent filter, a component can contain 0 or more Intent filter. Intent filter is written in the app's manifest file, which specifies the type of Intent that the component can handle by setting the action or URI data type. If you set intent Filter for your activity, this will make it possible for other apps to launch your activity through implicit intent. Conversely, if your activity does not contain any intent Filter, then the activity can only be started by an explicit intent, since we generally do not expose the full class name of our component, so in this case, Other apps are basically not able to start our activity through intent (because they don't know the full class name of the activity) and can only be started by our own app through explicit intent.

It should be noted that in order to ensure the security of the app, we should always use explicit intent to start the service and not set any intent Filter for that service. It is risky to start the service through an implicit intent because you are not sure which service in the end will start up in response to your implicit intent, and more sadly, because the service does not have a UI running in the background, So the user doesn't know which service is running. Starting with Android 5.0 (API level 21), using implicit intent to invoke the Bindservice () method, Android throws an exception, but there are techniques to convert an implicit intent to an explicit intent, Then use the explicit intent to call the Bindservice () method There is no problem, the specific solution can be found in the "Android in the process of communication between Messenger and service to achieve the final" Considerations "section, There is a solution for the relevant code.

Composition of the intent

Android can find the components to start based on the information intent carries, intent also carries some data so that the components to be started are processed according to the data in intent.

Intent consists of 6 pieces of information: Component Name, Action, Data, Category, Extras, Flags. Depending on the role of information, it can be divided into three categories:
A. Component name, Action, Data, category, the 4 information determines which component Android will launch, where Component name is used in an explicit intent, action, Data, Category, Extras, and flags are used in implicit intent.
B. Extras is a class that contains specific data information for the actual processing of the component.
C. Flags is a class of intent metadata that determines some of the behavior of Android on its operations, as described below.

Component name
The name of the component to start. If you want to use explicit intent, then you must specify this parameter, and once the component name,android is set, the intent is passed directly to the component specified by the component name to start it. If the component name is not set, then the intent is implicit, and the Android system makes some comparison decisions based on other intent information (such as action, data, category, etc.) to determine which component will eventually be started. So, if you start a component in your own app, you should start it by specifying component name through explicit intent (because you know the full class name of the component).

It is important to note that you should always specify component Name when starting the service. Otherwise, you are not sure which component of the app will be launched, and the user will not see which service started.

Component name in intent is the ComponentName object, and you can specify the value, such as com.example.ExampleActivity, by the full class name of the component you want to start, including the package name of the app. You can specify intent name through the intent SetComponent () method, the SetClass () method, the Setclassname () method, or the component constructor.

Action
is a string that represents the action to be performed, such as a view or selection, which corresponds to the action tag in the intent filter <action /> .

You can specify your unique action to use intent in your app or other apps to call components in your app via intent. Some classes in the intent class and other framework levels in Android also provide a number of well-defined actions that have a certain general meaning. Here are some common actions to start the activity:
Intent.ACTION_VIEWThe value is "Android.intent.action.VIEW", and when you have some information that you want to show to the user through other activity, you can designate the intent action as Action_view, For example, look at a picture in a picture application, or show a location in a map application.
Intent.ACTION_SENDThe value is "Android.intent.action.SEND", the action is often used for "sharing" use, when you have some data to be shared through other apps (such as QQ, Baidu Cloud, etc.), you can use this action to build intent object, and pass it to the StartActivity () method, because there may be more than one app on the phone activity support action_send This action, it is likely to appear in the picture below the situation as shown in the case of the user specifically choose which app to share your data:

You can learn more about some of the common actions intent predefined by looking at the intent class. Some of the classes at the framework level in Android also define actions, such as the actions that are defined in settings to open different interfaces of the "Settings" app in the system to complete the specified configuration (such as WLAN settings, language settings, etc.).

You can specify the intent action by calling the Setaction () method of the intent object or in the constructor of intent.

If you define your own action, be sure to prefix your app's package name with that action, which is a good programming habit to avoid confusion, such as:

staticfinal"com.example.action.TIMETRAVEL";

Data
The data in intent, referred to here, refers to the URI object and the MIME type of the data, which corresponds to the intent filter's data label <data /> .
A complete URI consists of scheme, host, port, path, and the format is <scheme>:// , for example content://com.example.project:200/folder/subfolder/etc . A URI is like a data link in which a component can obtain the final source of data based on this URI. The URI is usually used in conjunction with the action, for example we set the action to Action_view, and we should provide the URI of the document that will be modified by the edit.

When a intent object is created, it is also important to specify the MIME type of the data, in addition to specifying the URI. For example, an activity can display a picture, but cannot play a video, the URI that displays the picture and the URI that plays the video may be similar, in order not to let Android mistakenly pass a intent object containing the video URI to an activity that only shows the picture. We need to specify the MIME type as a picture (for example) in the activity's intent filter <data android:mimeType="image/*" ... /> and also to set the mime of the corresponding picture type to the intent object. Android will then pass intent to the eligible component based on the URI and MIME type. Then there is the exception, if the URI uses a content: protocol, then this means that the data provided by the URI will come from the local device, that is, the data is provided by ContentProvider, in which case Android automatically infers the MIME type based on the URI. In this case we no longer have to specify the MIME type ourselves.

If you only set the URI of the data, you need to call the SetData () method of the intent object, or if you only set the MIME type of the data, you need to call the Settype () method of the intent object, or if you want to set both the URI and MIME type of the data. You need to call the Setdataandtype () method of the intent object.

Note that if you want to set the URI and MIME type of the data at the same time, do not call the SetData () method and the Settype () method of the intent object successively, because the SetData () method and Settype () are mutually exclusive, that is, if the SetData is called () method resets the MIME type set by the Settype () method in intent to null. If the Settype () method is called, the URI already set by the SetData () method in intent is reset to null. So when you need to set both the URI and MIME type of the data, be sure to call the Setdataandtype () method of the intent object instead of calling the SetData () method and the Settype () method separately.

Category
The category contains some additional information about how the component handles intent, although it is possible to include any number of category in the intent, but most intent do not need category.
Here are some of the common category:

CATEGORY_BROWSABLEThe target component allows itself to be launched by a Web browser via a link, which may be an image link or an e-mail message.

CATEGORY_LAUNCHERUsed to identify activity as an entry activity for an app.

You can find more pre-defined categories in the intent class.

Extras
Extras, as the name implies, is the additional data information, intent has a bundle object stores a variety of key-value pairs, the component receiving the intent can read out the required information to complete the corresponding work. Some intent need to rely on the URI to carry data, and some intent to carry data information by extras.

You can add additional data in various key-value pairs to intent by calling the various overloaded Putextra (key, value) methods of the intent object. You can also create a bundle object directly, pass in many key-value pairs to the bundle object, and set it to the intent object by calling the Putextras (Bundle) method of the intent object.

For example, if you create a intent object with an action of action_send and then want to use it to start an e-mail message, you need to set the value of two extra for that intent object:
Set Intent.EXTRA_EMAIL the message header as the key value by setting the recipient as the key value Intent.EXTRA_SUBJECT .

The Intent class also specifies a number of predefined extra_* forms of extra, such as the ( Intent.EXTRA_EMAIL and) mentioned above Intent.EXTRA_SUBJECT . If you want to declare your own custom extra, be sure to prefix your app's package name with your extra, for example:

staticfinal"com.example.EXTRA_GIGAWATTS";

Flags
Flag is the meaning of the tag, and flags defined in the intent class can act as metadata for the intent object. These flags tell the Android system how to start the activity (for example, which task the newly initiated activity belongs to) and how to treat it after the activity is started (for example). More information can be found in the SetFlags () method of intent.

Example of an explicit intent use
new Intent(this, ActivityB.class);startActivity(intent);

The above code specifies in the intent constructor that the componentname of the component to be started is activityb, the intent object is explicit, and when startactivity (intent) is called, The Android system will start activityb immediately.

Implicit Intent Use example

As mentioned earlier, you need to specify an action when using implicit intent. If your app does not complete a feature, but other apps may be able to do that, you can use the implicit intent to launch other apps to do the right function. For example, if you have a text message that you want to share with other apps, then the implicit intent object is to launch a potentially shared app, with the sample code as follows:

intent sendintent = new  Intent () ; //set the action, the action is very important for the implicit Intent  sendintent.setaction (intent.action_send); Span class= "hljs-comment" >//setting data MIME type is plain text type  sendintent.settype ( "Text/plain" ); //set additional data  Sendintent.putextra (Intent.extra_text, textmessage); //get Package Manager  Packagemanager pm = Getpackagemanager (); //first to determine whether there is any potential app activity in the system to support the receipt and processing of the sendintent  if  (Pm.resolveactivity (sendintent, 0 )! = null ) {startactivity (sendintent);}  

In the above code, we built a intent object and did not set component name for it, so the intent is an implicit intent object. We first set the ACTION value for intent to intent.action_send,action is very important for implicit intent. We then set the MIME type of the intent data to the plain text type ("Text/plain"), informing Android that our intent holds the text type of data. Finally, we set the actual text data through the Putextra () method as additional data.
It is important to note that after building the intent object, we do not immediately execute the startactivity (sendintent) method, but instead pass the sendintent as a parameter to Packagemanager resolveactivity () method, this method allows Android to find information about a potentially appropriate startup component based on the sendintent, and returns the result as an object of the Resolveinfo class, if NULL is returned. Indicates that no component in the current system can receive and process the sendintent. If the return is not NULL, then there is at least one component in the system that can receive and process the sendintent, and only in this case do we execute code startactivity (sendintent). It is a good programming practice to judge that the component to start is not present before starting the component through intent, because if there is no component in the system that supports your intent, then when you call StartActivity (), StartService (), Bindservice () and other methods, Android throws an exception.

Force users to use app Chooser

As we have mentioned above, if our intent is implicit, when we try to start the component through StartActivity (intent), the Android system may display the file above asking the user which app to launch, Sometimes the user will set an app as the default app, so the next time we execute code startactivity (intent), it's possible that the app will not appear again, but instead run the app with the last user set as the default app. This is good for users who choose a default browser to open a Web page, because generally a user is accustomed to using a browser of their own liking.

But what if the user doesn't want to use the same default app each time to handle such a situation? At this time we can explicitly use the app selection dialog in the code, such as the party our app executes an action for action_send sharing function, we want to let users share their own data of the code, but we are not sure which app users want to share, We want to pop up the app selection dialog every time to let the user decide which app to share, the sample code looks like this:

Intent sendIntent = new Intent(Intent.ACTION_SEND);..."请选择想通过哪个App分享数据";// 验证是否有App能够接收并处理sendIntentif (sendIntent.resolveActivity(getPackageManager()) != null) {    // 根据sendIntent创建一个需要显示App选择对话框的intent对象    Intent chooserIntent = Intent.createChooser(sendIntent, title);    // 我们使用chooserIntent作为startActivity()方法的参数,而非sendIntent    startActivity(chooserIntent);}

First we created our original sendintent and set the action and other related information, and then we passed the sendintent to the Intent.createchooser () method and created another chooserintent. Later we call Intent.resolveactivity (Packagemanager) method to determine whether there are apps in the system to receive and process the sendintent, This method is equivalent to the resolveactivity () method of the Packagemanager mentioned above. Finally we use chooserintent as a parameter to the StartActivity () method, instead of sendintent,chooserintent the Android system to force the user to choose the interface that the app handles intent.

Most of this article refers to the description of the intent part of Android develop guide, and hopefully this article will help you better use the intent object.

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Intent overview and use of Android

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.