How to use Android intent

Source: Internet
Author: User

1. Description
Android provides a intent mechanism to assist in interaction and communication between applications or within applications.
Two basic usages of Intent: One is the explicit Intent, which is to specify the receiver when constructing the Intent object, similar to the normal function call, and the implicit Intent that the sender of Intent is constructing Intent the object, you do not know who the recipient is, just point out some of the characteristics of the receiver (such as starting music playback software)

2. How to use

1) Start the service

A) Key functions
Context.startservice () or context.bindservice ()

b) Example
Intent i = new Intent (this, mytestservice.class);
This.startservice (i);
start service

2) Send broadcast

A) Key functions
Context.sendbroadcast ()

b) Sending party
String msg = "Test";
Intent i = new Intent ("COM.TEST.BC");
I.pubextra ("msg", MSG);
This.sendbroadcase (i);

c) Receiving party
Intentfilter intentfilter = new Intentfilter ();
Intentfilter.addaction (Intent.action_media_eject);
Registerreceiver (Mreceiver.interfilter);

3) Start the application

A) Key functions
Context.startactivity ()

b) Example
Intent Intent =
New Intent ("Com.android.browser", "com.android.browser.BrowserActivity");
StartActivity (Intent);

3.     intent the composition of
Intent parameters can be much less, The system filters out one or more appropriate rules based on different combinations of parameters

1)           callers: Several rules can be specified at the same time, or you can specify part or parts of the
Component: Specifies the package name Class name to invoke (see above example Action: Specifies the rules for what to do action_dial specifies the dialing type applied
Data: Provides important data, usually uri, and also provides the type of data for filtering
Type: Used to specify the type for filtering Span Lang= "fr" (e.g. action_view is also specified as type for image, then the application of the browse picture is recalled Category: Specify the range
Extras: bundle class pass
Flags: Flag bit flag_activity_new_ Task specifies a new job )

2)           callee
in androidmanifest.xml in <intent-filter> declare rule
For example :  general procedures need to add lang= >inter-filter "fr" in ,  in order to be

3) Example
Intent Intent = new Intent ();
Intent.setclassname ("Com.android.browser",
"Com.android.browser.BrowserActivity");
Open Browser
Uri data = Uri.parse ("http://www.google.com");
Intent.setdata (data);
Open a webpage
Intent.addflag (Intent.flag_activity_new_task);
Open in new task mode
Intent.setaction (Intent.action_view);
Open in browse mode
StartActivity (Intent);

4. Intent's source code implementation

1) Intent analysis, filtering rules corresponding to the specific application
Frameworks/base/core/java/android/content/intentfilter.java

2) Intent definition, the corresponding relationship between the define used in the program and the string in XML
Frameworks/base/core/java/android/content/intent.java

5. Reference

Component-based architecture, in addition to well-defined components, how to assemble these components together is an art. In Android, Intent(seemingly usually translated: Intentions... ) is the bridge that connects the components. A while ago to see colleagues doing Symbian platform netease Palm Mail(really is do intentions, NB of a meter, warmly welcome all 163 mailbox S60v3 users, click ... ), there is a function to add attachments to the message, for example, you want to send a picture by mail bubble mm, you may need to have a very intuitive way to choose a collection of beautiful pictures from the local, or to take the camera to a perfect selfie. In Symbian, such a function, you need to use the underlying API, you write a little bit. In order to make the picture experience better, you may need to do something like a picture browser, in order to make the photo smoother, and even need to achieve a full range of camera functions, from focusing to adjusting brightness. In fact, the user's mobile phone may be installed in other professional image browser, camera and other applications, these applications have been very good to use, and users have been able to be purely using them, if the call can be made to the mailbox developers and users, will be a better choice. But in Symbian such a mistreated system, the application and application of the combination of the ability is very weak, want to reuse, basically more difficult than the sky, as a developer, can only endure again and again nausea, in order to users, do these repetitive wheel thankless additional work. Fortunately, in Android, everything is getting better, and it frees developers from the details of interfaces and objects, giving us more energy to focus on the development of core functions. In Android, if you need to choose a picture to make a movie, just construct a intent that describes your intention, send it out, and the system will help you choose a component that can handle the business to meet your needs, instead of having to tangle with specific interfaces and implementations, Perfect world, should be so.

Intent composition

Intent is translated intent, in fact, is still very expressive, intent expected to do, is the realization and the caller fully decoupled, the caller will concentrate on the intention to describe clearly, send out, you can dream come true, to achieve the purpose.

Of course, so to speak Taixu, discovering, what things cut to see, perhaps clear. Intentreference/android/content/intent.html), acting as a class in Android, initiating an intent, you need to construct such an object and assign values to some of the following:

  1. Action . There is always a verb in everyday life, when describing a wish or wish. For example: I want to do three push-ups, I want to see an X-ray, I want to write A history of blood and tears, and so on. In intent, an action is a description of what is seen, done, written, and so on, when you indicate an action, the executor will follow the instructions of the action, accept the relevant input, show the corresponding behavior, and produce the matching output. In the intent class, defined a number of actions, such as Action_view,Action_pick , and the like, the basic covers the common action, the whole of a dragon 18 palm complete. Of course, you can also keep up with the times and create new actions, like Lou. These custom actions have a limited range of flows compared to the predefined system, and unless you do a very NB application, everyone needs to follow you, otherwise it's usually the internal flow of the application.
  2. Data . Of course, the light is not enough to move, but also need to have more accurate object information. For example, the same is the action, but coffee , and girls , it is very bad. The description of data, in Android, behaves as a URI . Used in internal communication, may be described as content provider with the shape of content://xxxx such as the east, or an external form such as tel://xxxx such a link. In summary, it is a URI that clearly and accurately describes a data address.
  3. Type . When you say data, you have to mention the type, and many times, someone will misunderstand that the difference between data and type is just like the difference between a girl and a chick . But in fact, the type information is expressed in MIME , such as Text/plain , such things. Here, the difference between the two is very clear, the data is the house number, indicating the specific location, the specific problem of specific analysis, and type, is to emphasize the feather, to solve a batch of problems. The actual example is this, for example, a call from an application, will be initiated by the action is action_dial and data for tel:xxx such Intent, the corresponding human language is to call XXX phone , very elephant. And if you use type, it's a lot wider, like a browser receiving an unknown MIME type of data (such as a video ...). ), it will release such intent, the other system should be used to help, expressed as natural language should be: view PDF documents , such.
  4. Category . With action, with data or type, there are times when you can accurately express a complete intent, but there are times when you need to add some restraint in order to be more precise. For example, if you like to do push-ups, but do three at a time only in a special time will happen, then you may say: every time I eat , I want to do three push-ups. To eat, this corresponds to the category of intent, which attaches a constraint to the intention that occurs. In Android, an instance is that all applications are active (that is, the first activity that runs when you start it ...) ), it is necessary to be able to accept the intention of a CATEGORY of category_launcher,action as Action_main.
  5. Component . Before that, we tried to use Action,data/type,category to describe an intention, which is Android recommendation, and expect everyone to use it most of the time, so that the model is called implicit Intents in Android, This mode provides a flexible and extensible mode for users and third parties to apply an option. For example, or a mailbox software, most of his functions are good, is to choose the function of the picture is very earth, how to do? If it is implicit Intents, then it is an open system, no other picture selection program in the phone, you can continue to use the default mailbox, if there is, you can choose to replace the original module complete this function, everything is natural. But this mode, also is not without cost, need to pay is some performance overhead, because after all there is a retrieval process. As a result, Android offers another model, called Explicit Intents , that requires component help. Component is the class name , complete, shaped like com.xxxxx.xxxx , once indicated, everything is clear, find to this class (of course, it will be a specific subclass ...). ), success, vice versa, failure. This benefit, naturally, is speed, which is suitable for use when you explicitly know that this is an internal module.
  6. Extras . Through these items, the identification of the problem, the basic perfect solution, the remaining one important problem, is the transfer of parameters. Extras is used to do this thing, it is a Bundle class object, there is a set of serializable Key/value pairs composed. Each action, will have the corresponding key and value type Convention, when initiating intent, you need to follow the requirements of data can not be represented by the additional parameters into the extras (of course, if you do not need additional parameters, even if the ... ), or the performer will be mad when he gets it.
  7. Flags . can identify, there is input, the entire intent basic is complete, but there are some accessories instructions, need to put in the flags in the past. As the name implies, flags is a number of shapes, and there are some column flags that are used to indicate the mode of operation. For example, you expect the executor of this intent, and you to run in two completely different tasks (or the process is no harm ...). ), you need to set the flag_activity_new_task flag bit.

With these, a intent image of the leap off, so rich content, decided that it is more powerful than the traditional model.

Intent match last time in Moto Dev, listen to people do Android lectures, there are a lot of insofar on intent this concept expressed a strong interest, take out their familiar areas of the various concepts of analogy, such as events, messages and so on. At the time, I was thinking that intent as a communication protocol between components, unlike the general simple way of communicating, first, from the previous section, it is described in terms of requirements rather than the implementation. Second, it is based on a third party rather than two-party direct. This concept and the design pattern of the mediation mode (mediator pattern) is a pulse, that is, all the peripheral components, and only the core module of the system is connected, through which the relay, the components are not directly hooked up.


As shown, another important thing to run through the process is Intent Filters , which is used to describe a component such as activity or serveice, and what kind of Intent is expected to respond. If a component only wants other components to pass explicit Intents (that is, indicate component ... ) way to find it, then there is no need to add intent Filters, on the contrary, there must be one or several intent Filters. Intent filter of the various items, as if Intent in the mirror, including the effect of Action,catagory,data,type.

Intent filters can be written to the configuration file, and the configuration of those components together (do not remember what is the configuration file, you can see here ...) ), a number of instances can be found on the intent introduction page ( reference/android/content/intent.html)。 Similarly, the Intent filters can be dynamically plugged in the code, and this is a dynamic plug-and-pull Broadcast Receiveris used in the matching. The System core module is responsible for collecting these intent Filters, and their corresponding component information. When a requester needs a component to help, and constructs a Intent that describes its needs, it sends it to the core of the system, and the system core matches it to the known Intent filters, picking a component that meets the requirements to return. If there are multiple compliance, will try to see if there is no default execution, if there is no default, will construct the UI, let the user help choose, if so, the whole process ran through.

Intent implementation




is to request a simple implementation flowchart of an activity component, which is the most used intent parsing instance. The process starts with calling context.startactivity (Intent) , where the caller passes in the constructed Intent object, and the process is done by the actual performer, the instrumentation object. It is an activity manager that activates the entire application, centralizing the transforms death for all activity within the application. It has a hidden method Execstartactivit y method, which is responsible for starting the activity according to intent. To get rid of some details, the most important thing it does is to pass this call, via RPC, to activitymanagerservice .
In front of you, the core layer of the system, in fact, the so-called system core layer, is responsible for some of the key Android services . They also run on the virtual machine, and the common service implementation mechanism is consistent, but they do not throw their heads and face just silently in the next layer of service, so that the core of it. Acitivitymanagerservice, is responsible for activity scheduling services, may later mention the scheduling details will be involved.

Here, Acitivitymanagerservice will complete the relevant operation in two steps, first to submit the intent to another service Packagemanagerservice, the service has information about the entire package and its components, and it will match the intent passed over to all known intent filters (if there is component information ... ), found, the relevant component information back to Acitivitymanagerservice, here, will complete the start activity this many details of things. As a result, it is not a very lightweight process to start the activity and be processed by multiple services, and there is an assessment in the section on the performance of the Android random document. But this kind of operation is not put in the cycle of the type of repeated torture, so the overall effect and pay the performance cost compared to think is the value of the thing.

Original address: http://blog.csdn.net/liuyahui312031/article/details/6044887

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.