Explain the role and usage of intent in Android application development _android

Source: Internet
Author: User

Intent is a run-time binding (Run-time binding) mechanism that connects two different components during program operation. By intent, your program can express some kind of request or intention to Android, and Android will select the appropriate component to complete the request based on the content of the intention. For example, there is an activity that wants to open a Web browser to see the content of a Web page, and the activity only needs to issue web_search_action to android,android, according to intent's request, Query the Intentfilter of each component when registering, find the activity of the Web browser to browse the Web page.
Android's three basic components--activity,service and broadcast receiver--are activated through the intent mechanism, and different types of components have different ways of delivering intent:


To activate a new activity, or to have a new operation done by an existing one, you can either invoke the Context.startactivity () or the Activity.startactivityforresult () method.

To start a new service, or to pass a new instruction to an existing service, call the Context.startservice () method or call Context.bindservice () Method will call the context object of this method and the service binding.

The three methods of Context.sendbroadcast (), Context.sendorderbroadcast (), Context.sendstickbroadcast () can send broadcast Intent. Once sent, all registered broadcastreceiver that have matched intentfilter will be activated.
Once the intent is issued, Android will accurately find one or more matching activity,service or broadcastreceiver to respond. Therefore, different types of intent messages do not overlap, that is, broadcast intent messages are sent only to Broadcastreceiver and are never sent to an activity or service. Messages passed by StartActivity () are also sent only to the activity, and intent delivered by StartService () is sent only to the service.


composition of the intent

To pass data between different activity, it is necessary to include the corresponding content in the intent, in general, the most basic data should include:
Action: Used to indicate what action is to be implemented, such as Action_view, Action_edit, etc. You can refer to the Android.content.intent class in the Android sdk-> reference, where all the action is defined in constants.

Some of the most common action:

    • Action_call activity initiates a call.
    • The Action_edit activity displays the data edited by the user.
    • Action_main activity starts as the first activity in a task
    • Action_sync activity synchronizes data on a mobile phone with a data server.
    • Action_battery_low broadcast receiver Low battery warning.
    • Action_headset_plug broadcast receiver Plug headset warning
    • ACTION_SCREEN_ON broadcast the receiver screen to lighten the warning.
    • Action_timezone_changed broadcast receiver Change the time zone warning.

Activation of the Activity component

For each component, the method of activation is different:
1. To load (or assign a new job to) an activity by passing a intent object to context.startactivity () or Activity.startactivityforresult (). The corresponding activity can view the intent that activates it by calling the Getintent () method. Android is passed to its secondary intent by invoking the Onnewintent () method of the activity.

An activity often launches the next. If it expects the activity that it initiates to return a result, it replaces startactivity () with a call to Startactivityforresult (). For example, if it starts another activity so that the user picks a picture, it may want to know which photo is selected. The result is encapsulated in a intent object and passed to the Onactivityresult () method of the calling activity.

2. By passing a intent object to Context.startservice (), a service (or a new instruction is given to the running service) is started. The android invokes the OnStart () method of the service and passes the intent object to it.

Similarly, a intent can be passed to Context.bindservice () by the calling component to get a connection to a running target service. This service will get the intent object via the Onbind () method (if the service has not started, Bindservice () will start it first). For example, an activity can be connected to the aforementioned music playback service and provided to the user with an operable (user interface) to control playback. This activity can call Bindservice () to establish a connection and then invoke the object defined in the service to affect playback.

3. Applications can pass intent objects to Context.sendbroadcast (), Context.sendorderedbroadcast (), and Context.sendstickybroadcast () and other similar methods to produce a broadcast. Android calls the OnReceive () method of all broadcast receivers interested in this broadcast to pass intent to them.

What the Intent object contains

The variables for intent related content are defined in the Java source code of the intent class, as follows:

Action 
private String maction; 
Data 
private Uri mdata; 
Private String mtype; 
Private String mpackage; 
ComponentName 
private componentname mcomponent; 
Flag 
private int mflags; 
Category 
private hashset<string> mcategories; 
Extras 
private Bundle Mextras; 

1.componentName (component name), specifies the class name of the target component of the intent. The component name is optional, and if it is filled in, the intent object is sent to the component with the specified component name, otherwise the appropriate component can be located through other intent information. The component name is an object of type ComponentName.
Usage:

Intent Intent = new Intent (); 
The constructed parameter is the classpath name of the current context and target component 
componentname cn = New ComponentName (Helloactivity.this, " Com.byread.activity.OtherActivity "); 
Intent.setcomponent (CN); 
StartActivity (Intent); 

Equivalent to the following common methods:

Intent Intent = new Intent (); 
Intent.setclass (Helloactivity.this, otheractivity.class); 
StartActivity (intent); 
The Intent class also contains a constructor that initializes the ComponentName: public 

Intent (context Packagecontext, class<?> cls) { 
 mcomponent = New ComponentName (Packagecontext, CLS); 
 

2.action (action), specify the intent action, such as calling to call the component.

Public Intent (String action) { 
 maction = action; 
} 

3.data (data), which plays a role in representing data and MIME types of data. The different action is matched with a different data type, and is obtained by setting the URI of the data.

Public Intent (String action, Uri uri) { 
 maction = action; 
 Mdata = URI; 
} 

Call the calling component, for example:

Uri uri = uri.parse ("tel:10086"); 
Parameters are calls to invoke the ACTION of the calling component and the URI 
Intent Intent = new Intent (intent.action_dial, URI) for the data to be fetched; 
StartActivity (Intent); 

4.category (category), additional information about the action being executed. For example, the applied startup activity sets the category in Intent-filter.

<intent-filter> 
 <action android:name= "Android.intent.action.MAIN"/> 
 <category android: Name= "Android.intent.category.LAUNCHER"/> 
</intent-filter> 

5.extras (additional information) to provide additional information for processing the intent component. Information can be accessed through the PUTXX () and Getxx () methods, or by creating bundle objects and then by Putextras () and Getextras () methods.

6.flags (tag), which indicates how Android starts the target activity and sets the method to invoke the intent SetFlags method. The flags parameters that are commonly used are:

Flag_activity_clear_top
flag_activity_new_task
flag_activity_no_history
flag_activity_single_ Top 

Intent's Delivery

1. Explicit mode. Directly set the target component's componentname for a message delivery within an application, such as starting another activity or a services.
The componentname of the target component is established through intent's setcomponent and SetClass.

2. Implicit mode. The componentname is empty to invoke components in other applications. You need to include enough information so that the system can use intent filter to filter action, data, or category in all components to match the target component based on this information. can refer to the activity component in Android (5.Activity intent Filter)
If intent indicates that the action is set, then the target component's Intentfilter action list must contain this action, otherwise it cannot match;
If the intent does not provide a type, the system will get the data type from it. As with action, the target component's data type list must contain intent data types, otherwise it cannot match;
If the data in intent is not a URI of the content: type, and intent does not explicitly specify its type, the match will be based on the scheme of the data in intent (such as http: or mailto:). Ditto, Intent scheme must be present in the scheme list of the target component;
If intent specifies one or more category, these categories must all appear in the list of categories in the build. For example, intent contains two categories: Launcher_category and Alternative_category, the resolved target component must contain at least these two categories.

Intent invoke common system components

Call Browser Uri Webviewuri = Uri.parse ("Http://blog.csdn.net/zuolongsnail"); 
 
Intent Intent = new Intent (Intent.action_view, Webviewuri); 
Call map Uri Mapuri = uri.parse ("geo:100,100"); 
 
Intent Intent = new Intent (Intent.action_view, Mapuri); 
Play mp3 Uri Playuri = uri.parse ("File:///sdcard/test.mp3"); 
Intent Intent = new Intent (Intent.action_view, Playuri); 
 
Intent.setdataandtype (Playuri, "Audio/mp3"); 
Calls to call Uri Dialuri = Uri.parse ("tel:10086"); 
Intent Intent = new Intent (intent.action_dial, Dialuri); 
Call directly, need to add permissions <uses-permission id= "Android.permission.CALL_PHONE"/> Uri Calluri = Uri.parse ("tel:10086"); 
 
Intent Intent = new Intent (Intent.action_call, Calluri); 
Call Send email (here to configure the system in advance email, otherwise it is not set off the Mail interface) Uri Emailuri = Uri.parse ("mailto:zuolongsnail@163.com"); 
Intent Intent = new Intent (intent.action_sendto, Emailuri); 
Direct email Intent Intent = new Intent (intent.action_send); 
String[] tos = {"Zuolongsnail@gmail.com"}; String[] CCS = {"Zuolongsnail@163.com "}; 
Intent.putextra (Intent.extra_email, TOS); 
Intent.putextra (INTENT.EXTRA_CC, CCS); 
Intent.putextra (Intent.extra_text, "the email TEXT"); 
Intent.putextra (Intent.extra_subject, "SUBJECT"); 
Intent.settype ("Text/plain"); 
 
Intent.createchooser (Intent, "Choose Email Client"); 
Text message Intent Intent = new Intent (Intent.action_view); 
Intent.putextra ("Sms_body", "The SMS Text"); 
Intent.settype ("vnd.android-dir/mms-sms"); 
Direct SMS Uri Smstouri = Uri.parse ("smsto:10086"); 
Intent Intent = new Intent (intent.action_sendto, Smstouri); 
Intent.putextra ("Sms_body", "The SMS Text"); 
Send mms Uri Mmsuri = uri.parse ("Content://media/external/images/media/23"); 
Intent Intent = new Intent (intent.action_send); 
Intent.putextra ("Sms_body", "The SMS Text"); 
Intent.putextra (Intent.extra_stream, Mmsuri); 
 
Intent.settype ("Image/png"); 
Uninstall application Uri Uninstalluri = uri.fromparts ("package", "com.app.test", null); 
Intent Intent = new Intent (Intent.action_delete, Uninstalluri); Install application IntenT intent = new Intent (Intent.action_view); 
 
Intent.setdataandtype (Uri.fromfile) (New File ("/sdcard/test.apk"), "application/vnd.android.package-archive");   
Find the application URI URI in the android Market = Uri.parse ("market://search?q= Angry Bird"); 
 Intent Intent = new Intent (Intent.action_view, URI);

Note: Some need to configure certain permissions

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.