Explain how to use intent in Android _android

Source: Internet
Author: User

First, the 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 be started and other necessary data. For information on using the StartService () method to start a service, see the overview of basic usage of StartService in Android. for information on using the Bindservice () method to start a service, see the overview of basic usage of Bindservice in Android.
3. Send broadcast: Broadcasting is a kind of information that all apps can receive. The Android system publishes various types of broadcasts, such as a boot broadcast or a mobile phone charging broadcast. We can also send broadcasts to other apps, passing the intent object to the Sendbroadcast () method or the Sendorderedbroadcast () method or the Sendstickybroadcast () method to send a custom broadcast.

Ii. 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 start a component in your own app, because you know for sure the class name of the component you want to start. For example, in response to user action, you can start an activity in your app or start a service download file by using explicit intent.

Implicit Intent: If intent does not contain the complete class name of the component to be started, then the intent is implict, that is, implicit. Although implicit intent does not specify the class name of the component to be started, in general, an implicit intent specifies the action that needs to be performed. In general, an implicit intent is only used when we want to start another app's component in our app by intent, let another app's component receive and process the intent. For example, if you want to show the user a location 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, and ask for other map-like apps via this implicit intent (for example, Google Map, Baidu maps, etc.) to show a specific location on the map. Implicit intent also embodies a design philosophy of Android: My own app does not have all the functionality to offer users a good user experience by combining it with other apps. The link between your app and the rest of the app is an implicit intent.

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

When an implicit intent is created to use, the Android system filters 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 will be able to receive and handle the implicit intent. If a component in more than one app is eligible, Android pops up a dialog box that lets users choose which app to start.

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

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

Iii. composition of the intent

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

Intent consists of 6 pieces of information: Component Name, Action, Data, Category, Extras, Flags. Based on the role of information, and can be divided into three categories:
A. Component name, action, data, category for a class, these 4 information determines which component Android will start, where Component name is used in explicit intent, action, Data, Category, Extras, flags are used in an 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 how Android acts on its operations, as described below.

Component Name
The name of the component to start. If you want to use an explicit intent, you must specify the 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 component name is not set, then the intent is implicit, and the Android system makes some comparison judgments based on other intent information (such as the action, data, category, etc.) to decide which component to start. So, if you start a component in your own app, you should start it by specifying component name through an explicit intent (because you know the full class name of the component).

Note that when you start the service, you should always specify component Name. Otherwise, you're not sure which component of the app is eventually started, and the user doesn't see which service is starting.

The field that component name corresponds to in intent is a ComponentName object that you can specify by specifying the full class name (including the package name of the application) for the component you want to start, such as com.example.ExampleActivity. You can specify intent name by using 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 viewing or selecting, which corresponds to the action tag <action/> in intent filter.

You can specify your own action to facilitate the use of intent in your app or other apps to call your app's components in intent. Intent classes and other framework-level classes in Android also provide a number of well-defined action types that are already well defined. Here are some common action to start an activity:
Intent.action_view its 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 Intent ACTION as Action_ View, such as viewing a picture in a picture application, or displaying a position in a map application.
Intent.action_send its value is "Android.intent.action.SEND", which is often used for "sharing," when you have some data that you want to share with other apps (such as QQ, micro-mail, Baidu Cloud, etc.), You can use this action to build the intent object and pass it to the StartActivity () method, which supports the Action_send action because the activity of more than one app on the phone can So it is likely that the scenario shown below will allow users to specifically choose which app to share your data with:

You can learn more about intent predefined action by looking at the intent class. Some of the classes at the framework level in Android also define action, such as settings that define the action to open different interfaces for the "set" application in the system to complete the specified configuration (such as WLAN setup, language settings, and so on).

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

If you define your own action, be sure to prefix the action with the package name of your app, which is a good programming practice to avoid confusion, such as:

Copy Code code as follows:
Static final String Action_timetravel = "Com.example.action.TIMETRAVEL";

Data
Data in the intent described here refers to the MIME type of the URI object and data, which corresponds to the data label <data/> in intent filter.
A complete URI consists of scheme, host, port, and path, in the form of <scheme>://

When creating a intent object, the MIME type of the specified data is also important in addition to specifying a URI. For example, an activity can display a picture, but it cannot play the video, and the URI of the picture and the URI that plays the video may be similar, in order not to allow Android to mistakenly pass a intent object containing the video URI to an activity that can only display pictures, We need to specify the MIME type in the activity's intent filter as a picture (for example, <data android:mimetype= "image/*" .../> And also set the mime of the corresponding picture type to the intent object, so that Android passes intent to the eligible component based on the URI and MIME type. Then there is the exception, if the URI uses the 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 do not have to specify the MIME type again.

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

Note that if you want to set both the URI and the MIME type of the data, do not call the intent object's SetData () method and the Settype () method successively, because the SetData () method and the Settype () are mutually exclusive, that is, if you call the SetData () method, resets the MIME type that has been set in intent through the Settype () method to null. If the Settype () method is invoked, the URI that is already set by the SetData () method in intent is reset to null. So when you need to set both the URI and the 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 individually.

Category
Category contains some additional information about how the component handles intent, although any number of category can be added to the intent, but most intent do not need category.
Here are some common category:

The category_browsable target component allows itself to be started by a Web browser via a link that may be a picture link or e-mail message.

Category_launcher is used to identify an activity as an entry activity for an app.

You can find more predefined category in the intent class.

Extras
Extras, as the name suggests, is the additional data information, intent has a bundle object that stores various key-value pairs, and receives the intent component to read out the required information in order to complete the work accordingly. Some intent need to carry the data by the URI, some intent rely on the extras to carry the data information.

You can add additional data in the form of various key-value pairs to the 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 then set it to the Bundle object by calling the intent object's Putextras (intent) method.

For example, if you create an intent object that has an action as action_send and then want to use it to initiate e-mail messages, you need to set a value of two extra to the intent object:
Set the Intent.extra_email as the key value and use Intent.extra_subject as the key value to set the message header.

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

Copy Code code as follows:
Static final String Extra_gigawatts = "Com.example.EXTRA_GIGAWATTS";

Flags
Flag is the meaning of the mark, and the flag defined in the intent class can act as metadata for the intent object. These flag will tell the Android how to start an activity (for example, which task the newly initiated activity belongs to) and how to treat it after the activity starts (for example). See the intent SetFlags () method for more information.

1, the use of explicit intent example

Intent Intent = new Intent (this, activityb.class);
StartActivity (Intent);

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

2. Examples of implicit intent usage

As mentioned before, you need to specify an action when using implicit intent. If your app doesn't perform a function, but other apps may be able to do that, you can use an implicit intent to start other apps to do the same function. For example, if you have a text message that you want to share with other apps, the implicit intent object launches the potential support-sharing app with the sample code as follows:

Intent sendintent = new Intent ();
Set action, action is very important for implicit Intent
sendintent.setaction (intent.action_send);
Sets the MIME type of the data to be a plain text type
sendintent.settype ("Text/plain");
Set additional data
Sendintent.putextra (Intent.extra_text, textmessage);

Get Package Manager
Packagemanager pm = Getpackagemanager ();
First, determine if there are any potential app activity in the system that supports receiving and processing the sendintent
if (pm.resolveactivity (sendintent, 0)!= null) {
 StartActivity (sendintent);
}

In the code above, we built a intent object and did not set component name on it, so the intent is an implicit intent object. We first set the value of the ACTION to intent intent.action_send,action is very important to the implicit intent. We then set the MIME type of the intent data to a plain text type ("Text/plain"), telling Android that our intent holds text-type data. Finally, we set the actual text data into the additional data through the Putextra () method.
It should be noted that after building the intent object, we did not immediately execute the startactivity (sendintent) method, but instead passed sendintent as a parameter to Packagemanager's resolveactivity () method, this method allows Android to find information about the potential for the 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, it indicates that there is at least one component in the system that can receive and process the sendintent, and only in this case will we execute code startactivity (sendintent), It is good programming practice to decide that the component to be started is not present before you start the component through intent, because if the component that supports your intent is not present in the system, then when you call StartActivity (), StartService (), Bindservice () and other methods, Android throws an exception.

Iv. forcing users to use app Chooser

As we mentioned earlier, if our intent is implicit, and when we try to start the component through StartActivity (intent), the Android system may display the screenshot file asking the user which app to start. Sometimes the user will set a certain app as the default app, so that the next time we execute code startactivity (intent), we may not be able to choose the app interface, but run the last user set as the default app. This is good for a user to choose a default browser to open a Web page, because generally one user is accustomed to using a browser of their own preference.

But what if the user doesn't want to handle the same default app every time? At this point we can explicitly use the app selection dialog in the code, such as when the party our app performs an action-action_send sharing function, we want users to share the code for their data, but we're not sure which app they want to share, We want to pop the app selection dialog every time and let the user decide which app to share, as shown in the sample code:

Intent sendintent = new Intent (intent.action_send);
...

String title = "Please choose which app you want to share data with";

Verify that there is an app that can receive and process sendintent
if (sendintent.resolveactivity (Getpackagemanager ())!= null) {
 // According to Sendintent, create a Intent object that needs to display the App selection dialog box
 Intent chooserintent = Intent.createchooser (sendintent, title);
 Instead of Sendintent
 startactivity (chooserintent), we use chooserintent as a parameter to the StartActivity () method;


First we created our original sendintent and set the relevant information for the action, and then we passed sendintent to the Intent.createchooser () method and created another chooserintent. We then call the Intent.resolveactivity (Packagemanager) method to determine if there are any apps in the system that can receive and process sendintent. This method is equivalent to the Packagemanager resolveactivity () method mentioned above. Finally, we use chooserintent as a parameter to the StartActivity () method, rather than sendintent,chooserintent, which forces the Android system to display the interface that the user chooses the app to handle intent.

Most of this paper refers to the Android intent part of the Develop guide description, I hope this article for the better use of intent objects help.

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.