Android Note 5. deep understanding of Intent and IntentFilters (1)

Source: Internet
Author: User

Android Note 5. deep understanding of Intent and IntentFilters (1)
Deep understanding of Intent and IntentFiler (1)Jiangdg_VIPHttp://blog.csdn.net/u012637501In order to have a deep understanding and flexible use of Intent, I plan to divide this part of learning into two steps: one is to thoroughly understand the basic concepts and classes of Intent; the other is, this section describes how to use Intent to start a component and transfer data between components through instances.1. What is Intent?Android applications include three components: Activity, Service, and BroadcastReceiver. To facilitate communication between different components, the application uses a unified method to start components and transmit data, use Intent. Intent encapsulates the "Intent" of a component that Android applications need to start. The Intent class object is the communication carrier between components, and an Intent object is a set of information, it contains the information (such as action and Data) Concerned by the Intent component and the information (such as Category) Concerned by the Android system ). That is to say, the Component that sends an "Intent" starts a specified (Component Attribute) or a specified (some) by filtering (Action & Category attribute) through the content contained in the Intent object) component, and then implement the corresponding Action (that is, the Action attribute) and pass the corresponding Data (that is, the Data attribute) to complete the corresponding Action.2. How does Intent implement mutual calls between components?1. Intent implementationThe simple implementation flowchart of requesting an Activity component is the most commonly used Intent parsing instance. First, send the "intent" component by calling Context. startActivity (intent) starts the component: the component that sends an "Intent" to pass in the constructed intent object (a group of information, which determines whether another component can be successfully started). Then, calling "action" actually executes the Instrumentation object. It is the Activity manager activated by the entire application and is responsible for running all the activities in the application. It has a hidden method called execStartActivity, which is used to start the Activity based on Intent. This method removes some details. The most important thing it does is to pass the call to ActivityManagerService through RPC. Finally, ActivityManagerService will submit the key information to another service PackageManagerService. This service will master the information of the entire software package and its components, and it will pass the Intent, match with all the known Intent Filters (if there is Component information, there is no need to compare ). If it finds out, it notifies AcitivityManagerService of the relevant Component information. Here, many details about starting the Activity will be completed.2. Intent matchIn the end, how do I find the required components for components that send "intentions? Intent Filters starts to take effect. Intent Filters is defined in the AndroidMainFest. xml file, and each Activity has Element, which contains,. This "intent" is called "intent" when our intent object does not contain Component information ". That is to say, "intention" does not specify the component to be started and the action to be done. In this case, we need to match the information through the sub-elements in Intent Filters to determine whether the Activity that currently contains the Intent Filters attribute is the (some) component we want to start. The sending "intent" component configures the Intent object, and the started component implements the intent Filters attribute. Finally, the sending component configures the Intent object according to the AndroidMainFest. xml Information to determine whether it is a target component.Iii. Explanation of Intent objectsIntent objects are the communication carriers between components. Using Intent objects, we can easily implement communication between different components. An Intent object is a set of information, which is reflected by its Component, Action, Category, Data, Extra, and Flag attributes. Intent indicates the Android app's "intention" to start. The Android app starts a specified component based on the Intent. The Intent attribute determines which component to start.1. Action attributesThe Action attribute is a common string that represents the "Action" to be completed by the Intent object ". When we specify an action for the Intent object, the started component will show the corresponding behavior according to the action instructions, such as viewing, dialing, editing, etc, note that a component (such as Activity) can only have one action. We can facilitate the communication between our application components and customize the action (string) to create new actions. We can also directly use static member variables in the Intent class, such as ACTION_VIEW, ACTION_PICK, they are a batch of action variables predefined for the action attribute in Android. When setting the Action attribute of an Intent object, there are two types:

(1) custom String public final String CUSTOME_ACTION = "intent. action. CUSTOME_JIANG "; // string can be any Intent intent = new Intent (); intent. setAction (ActionAttr. CUSTOME_ACTION); // Note: ActionAttr is the class we created. You can also use this. CUSTOME_ACTION (2) use the system-scheduled action constant Intent intent = new Intent (); intent. setAction (Intent. ACTION_CALL); // Where ACTION_CALL is the static member variable of the Intent class, which can be called directly by the class // corresponding string "android. intent. action. CALL"
2. Data attributesThe Action attribute describes an "Action" for the Intent object, so the Data attribute provides operation Data for the Action attribute of the Intent object. Note that the Data attribute only accepts one Uri object. A Uri object is usually represented by a string in the following format: Uri string format: scheme: // host: example of port/path: content: // com. android. contacts/1 or tel: // 18819463209 when setting the Data attribute of the Intent object, you can do this:
Intent intent = new Intent (); String data = "content: // com. android. contacts/1 "; Uri uri = Uri. parse (data); // converts a string to Uriintent. setData (uri); or Intent intent = new Intent (); intent. setData (Uri. parse ("content: // com. android. contacts/1 "));
Blogger NOTE 1: The action attribute and data attribute are the main parts of the information transmitted by Intent, and the action/data Attribute example: ACTION_VIEW content: // contacts/people/1 -- the transmitted information: show the information about the person with the number of 1 ACTION_DIAL content: // contacts/people/1 -- transfer information: Call the person with the number of 1 to call ACTION_VIEW tel: 123 -- transfer information: show ACTION_DIAL tel: 123 -- transfer information: Call 123ACTION_EDIT content: // contacts/people/1 -- transfer information: edit the contact ACTION_VIEW content numbered 1: // contacts/people/-- message: lists all contacts. if you want to view a contact, you need to define a new intent and The property is set to {ACTION_VIEW content: // contacts/N} and passed to a new Activity. Conclusion: The action and data attributes are the main attributes of intent. 3. Catagory attributesAction can be used together with the Data or Type attribute to accurately express a complete intent. However, to make the "intent" more accurate, we also add some constraints to the intent, which is implemented by the Catagory attribute of the "intent. One intent can only specify one action attribute, but one or more Catagory attributes can be added. The Category attribute can be implemented using custom strings, but the predefined Category constant can be set to facilitate communication between different applications. Call addCategory to add a Category for the Intent, and removeCategory to remove a Category; the getCategories method returns the defined Category. You can set the Categoty attribute of the Intent object as follows:
(1) custom String public final String CUSTOME_CATEGORY = "intent. action. CUSTOME_CATEGORY "; // string can be any Intent intent = new Intent (); intent. addCategory (ActionAttr. CUSTOME_CATEGORY); (2) use the following code of the system scheduled action and category constants to return the HOME desktop through the Intent object when a button is clicked. Intent intent = new Intent (); intent. setAction (Intent. ACTION_MAIN); intent. addCategory (Intent. CATEGORY_HOME); // return Home Desktop
Blogger NOTE 2: Generally, both Action and Category attributes are used at the same time. In Android, all the main activities (that is, the first Activity to run when the app is started independently...) must be able to accept the intent of CATEGORY_LAUNCHER and Action as ACTION_Main. For components that send "intent", you can use the setAction () and addCategory () Methods to add the action attribute for "intent" or add the Action and Category attributes at the same time; for components that receive "intent", in AndroidManifest. in the xm file, we can set it as follows: // Default Action // Default Category // Default Category Note: The Activity that sends an "intent" changes Category to CATEGORY_LAUNCHER and Action to ACTION_Main. The Activity that receives the "intent" must set a default Category attribute CATEGORY_DEFAULT, you cannot set it to CATEGORY_LAUNCHER. Otherwise, an error is returned. In addition, if we use the predefined action constant, we need to add the corresponding permissions to the AndroidManifest. xm file. We will discuss this in the second part. 4. Type attributesThe Type attribute is used to specify the MIME Type corresponding to the specified Uri of the Data. This Type can be any custom MIME Type, as long as the string conforms to the abc/xyz format. Note that the Type and Data attributes usually overwrite each other. If you want the Intent to have both the Data attribute and the Type attribute, you must use the setDataAndType () method. For the understanding of the Type attribute, I remember a blog post for example: if we talk about Data, we must mention the Type. In many cases, some people may misunderstand it, the difference between Data and Type is almost the same as that between a girl and a girl. But in fact, the Type information is represented by MIME, such as text/plain. Here, the difference between the two is very clear. Data is the house number, indicating the specific location and specific analysis of specific problems, and type is to emphasize that things are clustered to solve the problem of batch. The actual example is as follows. For example, when a call is made from an application, the action is ACTION_DIAL and the data is Intent such as tel: xxx, the corresponding human language is the call to xxx, which is very representative. If type is used, it is much broader. For example, the browser receives an unknown MIME type data (such as a video ...), this kind of Intent will be released, and other applications of the system will be requested for help. The natural language of a table should be: viewing pdf documents. Blogger Note 3: MIME type? MIME (Multipurpose Internet Mail Extensions) multi-purpose Internet Mail Extension type is to set a file extension to open in an application type, when the extension file is accessed, the browser automatically opens the application with the specified application. It is used to specify custom client file names and open media files. In the earliest HTTP protocol, there was no additional data type information. All transmitted data was interpreted by the client program as HTML documents in the hypertext markup language. to support multimedia data types, the MIME data type information appended to the document is used in the HTTP protocol to identify the data type. MIME is a multi-function Internet Mail Extension designed to attach multimedia data to an email so that the mail client program can process it based on its type. However, when it is supported by the HTTP protocol, its meaning becomes more significant. It makes HTTP transmitted not only plain text, but also rich and colorful. Each MIME type consists of two parts. The front part is a large data type, such as audio, image, and so on. The latter part defines a specific type. Common MIME type (general type): hypertext markup language text. html text/htmlxml document. xml text/xmlXHTML document. xhtml application/xhtml + xml plain text. txt text/plainRTF text. rtf application/rtfPDF document. pdf application/Microsoft Word file. word application/mswordPNG image. png image/pngGIF image. gif image/gifJPEG image. jpg image/jpegau audio file. au audio/basicMIDI music file mid ,. midi audio/midi, audio/x-midiRealAudio music file. ra ,. ram audio/x-pn-realaudioMPEG file. mpg ,. mpeg video/mpegAVI file. avi video/x-msvideoGZIP file. gz application/x-gzipTAR file. tar application/x-tar any binary data application/octet-stream 5. Ertras attributesThrough the above items, we can identify the problem and solve it perfectly. The next important problem is passing parameters. Extras is used to do this. It is a Bundle Class Object and consists of a set of serializable key/value pairs. Each Action has a corresponding key and value Type Convention. When initiating an Intent, you need to add extra parameters not represented by Data to Extras as required. 6. Flags attributesThe entire Intent can be identified and input is complete, but some attachment commands need to be included in Flags. As the name suggests, Flags is an integer with the flag spaces of some columns. These Flags are used to specify the running mode. For example, if you want the executor of this intent to run in two completely different tasks (or process is fine...), you need to set the FLAG_ACTIVITY_NEW_TASK flag. 7. Component attributesGenerally, "intent" can be divided into display intent and implicit intent. Intent Filters is used to describe an Activity or Serveice component. The Intent element to meet the expected response. This method is called implicit intent without specifying the component name to be started. Of course, we can also enable "intent" to start a specified Component, that is, display intent, which is mainly implemented through the Component attribute. The Component Attribute of Intent needs to accept a ComponentName object, which binds the class name and package name of the specified Component to be started to the intent.
ComponentName comp = new ComponentName (ComponentAttr. this, SecondaryActivity. class); Intent intent = new Intent (); intent. setComponent (comp); // set the Component Attribute of intent and specify the package and Class Name of the "intent" Component to be started. Note: The first sentence is used to create a ComponentName object, to specify the package name and type-this uniquely identifies a component class.
Iv. Intent-related classes 1. Activity ClassHere we only need to learn how to use Intent to start the Activity component.
Void StartActivity (Intent intent): starts an Activity. The intent attribute determines which Activity to start and how to start it.
Void StartActivityForResult (Intent intent, int requestCode): starts the Activity and returns a result. When the started Activity exits, the onActivityResult () method is called and a requestCode parameter is passed to it. The requestCode parameter is not negative (> 0 ), the function is to indicate which Activity component sends the "intent". Note that if requestCode is less than 0, this method can only be used to start an Activity and cannot return a value. In addition, the Intent action attribute is set to be able to return a result. If it is setIntent.ACTION_MAINOrIntent. ACTION_VIEW cannot obtain the result.
To be written: there are also methods for starting the Service and BroadcastReceiver components. I will learn more later. 2. Intent class(1) constructor

Intent (): Create an empty constructor Intent (Intent o): copy constructor

Intent (String action): creates an Intent object with the acion attribute

Intent (String action, Uri uri): creates an Intent with the action attribute and accepts a Uri object.

Intent (Context packageContext, Class Cls): creates an intent for a specified component.

Intent (String action, Uri uri, Context packageContext, Class Cls) creates an intent with the action and data attributes for a specified component.
(2) Common Methods
Intent AddCategory (String category) Add a new category to the intent.
Intent AddFlags (int flags) Add additional flags to the intent (or with existing flags value ).
String GetAction () Retrieve the general action to be performed med, suchACTION_VIEW.
Set GetCategories () Return the set of all categories in the intent.
ComponentName GetComponent () Retrieve the concrete component associated with the intent.
Uri GetData () Retrieve data this intent is operating on.
Bundle GetExtras () Retrieves a map of extended data from the intent.
Int GetFlags () Retrieve any special flags associated with this intent.
Static Intent GetIntent (String uri) This method was deprecated in API level 4. UseparseUri(String, int)Instead.
String GetPackage () Retrieve the application package name this Intent is limited.
String GetScheme () Return the scheme portion of the intent's data.
Intent GetSelector () Return the specific selector associated with this Intent.
Rect GetSourceBounds () Get the bounds of the sender of this intent, in screen coordinates.
String GetType () Retrieve any explicit MIME type encoded in the intent.
Boolean HasCategory (String category) Check if a category exists in the intent.
Boolean HasExtra (String name) Returns true if an extra value is associated with the given name.
Static Intent MakeMainActivity (ComponentName mainActivity) Create an intent to launch the main (root) activity of a task.
Static Intent Makemainselectshorttition (String selectshorttion, String selectorCategory) Make an Intent for the main activity of an application, without specifying a specific activity to run but giving a selector to find the activity.
Static Intent ParseIntent (Resources resources, XmlPullParser parser, AttributeSet attrs) Parses (resolution) the "intent" element (and its children) from XML and instantiates an Intent object.
Static Intent ParseUri (String uri, int flags) Create an intent from a URI.
Intent PutExtra (String name, int value) Add extended data to the intent.
Intent PutExtra (String name, CharSequence value) Add extended data to the intent.
Intent SetAction (String action) Set the general action to be performed med.
Intent SetClass (Context packageContext, Class Cls) Convenience for callingsetComponent(ComponentName)With the name returned byClassObject.
Intent SetClassName (Context packageContext, String className) Convenience for callingsetComponent(ComponentName)With an explicit class name.
Intent SetClassName (String packageName, String className) Convenience for callingsetComponent(ComponentName)With an explicit application package name and class name.
Intent SetComponent (ComponentName component) (Usually optional) Explicitly set the component to handle the intent.
Intent SetData (Uri data) Set the data this intent is operating on.
Intent SetFlags (int flags) Set special flags controlling how this intent is handled.
Intent SetPackage (String packageName) (Usually optional) Set an explicit application package name that limits the components this Intent will resolve.
Void SetSourceBounds (Rect r) Set the bounds of the sender of this intent, in screen coordinates.
Intent SetType (String type) Set an explicit MIME data type.
String ToString () Returns a string containing a concise (concise), human-readable (readable) description of this object.
String ToUri (int flags) Convert this Intent into a String holding a URI representation of it.
(3) Class static member variables, such as ACTION and CAYEGORY constants, are called by Intent or its objects to set intent attribute. the following Actions constants of the standard Activity actions are used to define Intent for operations on various activities. They are usually implemented using the startActivity (Intent) method.
  • ACTION_MAIN // pass the action returned to the main Activity
  • ACTION_VIEW // pass the Display Action
  • ACTION_ATTACH_DATA
  • ACTION_EDIT // pass the edit action
  • ACTION_PICK
  • ACTION_CHOOSER // transfer the selection action
  • ACTION_GET_CONTENT
  • ACTION_DIAL
  • ACTION_CALL
  • ACTION_SEND
  • ACTION_SENDTO
  • ACTION_ANSWER // receives the call.
  • ACTION_INSERT
  • ACTION_DELETE
  • ACTION_RUN
  • ACTION_SYNC
  • ACTION_PICK_ACTIVITY
  • ACTION_SEARCH
  • ACTION_WEB_SEARCH
  • ACTION_FACTORY_TESTB. Standard Broadcast ActionsThe following "intent" action attribute constant is used to receive broadcasts. Generally, the registerReceiver (BroadcastReceiver, IntentFilter) method is used or defined in the AndroidManifest. xml file. Activity of the property.
    • ACTION_TIME_TICK
    • ACTION_TIME_CHANGED
    • ACTION_TIMEZONE_CHANGED
    • ACTION_BOOT_COMPLETED
    • ACTION_PACKAGE_ADDED
    • ACTION_PACKAGE_CHANGED
    • ACTION_PACKAGE_REMOVED
    • ACTION_PACKAGE_RESTARTED
    • ACTION_PACKAGE_DATA_CLEARED
    • ACTION_UID_REMOVED
    • ACTION_BATTERY_CHANGED
    • ACTION_POWER_CONNECTED
    • ACTION_POWER_DISCONNECTED
    • ACTION_SHUTDOWNC. Constant of standard CategoriesAdd additional category information to the Action. The addCategory (String category) method is usually used.
      • CATEGORY_DEFAULT
      • CATEGORY_BROWSABLE
      • CATEGORY_TAB
      • CATEGORY_ALTERNATIVE
      • CATEGORY_SELECTED_ALTERNATIVE
      • CATEGORY_LAUNCHER
      • CATEGORY_INFO
      • CATEGORY_HOME
      • CATEGORY_PREFERENCE
      • CATEGORY_TEST
      • CATEGORY_CAR_DOCK
      • CATEGORY_DESK_DOCK
      • CATEGORY_LE_DESK_DOCK
      • CATEGORY_HE_DESK_DOCK
      • CATEGORY_CAR_MODE
      • CATEGORY_APP_MARKETD. Standard Extra Data constantUse the putExtra (String, Bundle) method.
        • EXTRA_ALARM_COUNT
        • EXTRA_BCC
        • EXTRA_CC
        • EXTRA_CHANGED_COMPONENT_NAME
        • EXTRA_DATA_REMOVED
        • EXTRA_DOCK_STATE
        • EXTRA_DOCK_STATE_HE_DESK
        • EXTRA_DOCK_STATE_LE_DESK
        • EXTRA_DOCK_STATE_CAR
        • EXTRA_DOCK_STATE_DESK
        • EXTRA_DOCK_STATE_UNDOCKED
        • EXTRA_DONT_KILL_APP
        • EXTRA_EMAIL
        • EXTRA_INITIAL_INTENTS
        • EXTRA_INTENT
        • EXTRA_KEY_EVENT
        • EXTRA_ORIGINATING_URI
        • EXTRA_PHONE_NUMBER
        • EXTRA_REFERRER
        • EXTRA_REMOTE_INTENT_TOKEN
        • EXTRA_REPLACING
        • EXTRA_SHORTCUT_ICON
        • EXTRA_SHORTCUT_ICON_RESOURCE
        • EXTRA_SHORTCUT_INTENT
        • EXTRA_STREAM
        • EXTRA_SHORTCUT_NAME
        • EXTRA_SUBJECT
        • EXTRA_TEMPLATE
        • EXTRA_TEXT
        • EXTRA_TITLE
        • EXTRA_UIDE. FlagsSet the flags attribute of intent through setFlags (int) and addFlags (int.
          • getFlags()
          • addFlags(int)
          • FLAG_GRANT_READ_URI_PERMISSION
          • FLAG_GRANT_WRITE_URI_PERMISSION
          • FLAG_GRANT_PERSISTABLE_URI_PERMISSION
          • FLAG_GRANT_PREFIX_URI_PERMISSION
          • FLAG_DEBUG_LOG_RESOLUTION
          • FLAG_FROM_BACKGROUND
          • FLAG_ACTIVITY_BROUGHT_TO_FRONT
          • FLAG_ACTIVITY_CLEAR_TASK
          • FLAG_ACTIVITY_CLEAR_TOP
          • FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET
          • FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS
          • FLAG_ACTIVITY_FORWARD_RESULT
          • FLAG_ACTIVITY_LAUNCHED_FROM_HISTORY
          • FLAG_ACTIVITY_MULTIPLE_TASK
          • FLAG_ACTIVITY_NEW_DOCUMENT
          • FLAG_ACTIVITY_NEW_TASK
          • FLAG_ACTIVITY_NO_ANIMATION
          • FLAG_ACTIVITY_NO_HISTORY
          • FLAG_ACTIVITY_NO_USER_ACTION
          • FLAG_ACTIVITY_PREVIOUS_IS_TOP
          • FLAG_ACTIVITY_RESET_TASK_IF_NEEDED
          • FLAG_ACTIVITY_REORDER_TO_FRONT
          • FLAG_ACTIVITY_SINGLE_TOP
          • FLAG_ACTIVITY_TASK_ON_HOME
          • FLAG_RECEIVER_REGISTERED_ONLYReference: http://developer.android.com/reference/android/net/Uri.html

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.