Android Official Docs app components (Intents and Intent Filters)

Source: Internet
Author: User

The Android application framework encourages developers to reuse components as they develop their applications, and this article explains how to build applications using components and how to connect components with intent.
If you want to read the official text, please click on this link:

"Apps".

You can also refer to these blog posts:

    • "Using dialogfragments"

    • "Fragments for All"

    • "Multithreading for Performance"

And these training:

    • "Managing the Activity Lifecycle"

    • "Building a Dynamic UI with fragments"

    • "Sharing Content"

Intent and Intent Filters (Intents and Intent Filters)

Intent is an object that delivers messages, you can specify an action for intent to launch other application components, intent make communication between components more convenient, and there are many ways to communicate, here's a list of the main three points:

    • Start activity:

      You can use intent as a parameter to invoke the StartActivity () method to start an activity. The intent describes the characteristics of the target activity that will be launched and carries the necessary data information. You can also call the Startactivityforresult () method for callback information.

    • Start Service:

      The service is used to perform tasks in the background without interacting with the user. You can use the StartService () method to perform a one-time operation (for example, after downloading a file in the console), which requires the intent parameter.
      If you need to communicate with the CS structure between components, you can think of the service as one end and call Bindservice (), which also requires the intent parameter.

    • Pass a broadcast:
      Broadcast is a broadcast mechanism that can be intercepted by any application. You can call Sendbroadcast (), Sendorderedbroadcast (), Sendstickybroadcast () based on the events that are currently occurring, such as when the device is powered on, when it starts charging, and so on broadcast () method to send a broadcast, which requires passing in the intent parameter.

Types of Intent (Intent Types)
    • Explicit intent: Starts a component by specifying a specific class name. Explicit intent are typically used within the same application because you can be sure of the name of the component you want to start. Additionally, Android 5.0 specifies that the service must be explicitly started.

    • Implicit intent: When you want to start a component that has some kind of feature, you can use implicit intent, an implicit intent without specifying a class name, which is typically used to start a component of another application, such as an activity where you intend to launch a map targeting.

When you start a service or activity implicitly, intent matches the intent-filter of the manifest file in the other component according to its contents, launches the qualifying component, and passes the parameters in the intent. If more than one intent-filter satisfies the condition, a dialog box pops up and the user decides which component to start. Here is the intent with intent-filters to start the component:

See:
1, first activity A to use the incoming intent call startactivity ();
2, the system will be based on the conditions of the intent to search all the matching components of the Android system;
3. If the component (Activity B) that matches the intent intent-filters is found, the component is started and the OnCreate () method is recalled, and the intent is passed in the past.

Intent-filters is a label inside a component in the manifest file that describes what the component has, and if you do not configure intent-filters, that component can only be explicitly started.

Create Intent object (Building an Intent)

The intent contains the attributes that the target component needs to satisfy. The following information should be included in the intent:

    • Component Name: The name of the target component. For an explicit start, this is not a default, you can use the intent constructor method to pass in the component name, or you can call SetComponent (), SetClass (), Setclassname () These methods to pass in the component name, if the implicit start, this is optional, However, intent should contain additional information (action, category, data);

    • Action: is a string that can indicate the behavior of the target component. The action largely determines the information that should be passed in category and data; You can also specify an action in your own application component to let other applications launch their own components. The string corresponding to the action is not recommended in hard-coded form, but should be set to a constant in the class of the owning component.

      Common action is:

      • Action_view: Activity initiated with action _view can typically present information to the user, such as activating an activity in a photo album app to display an image, or launching an activity that displays address information in a map app.
      • Action_send: It is generally necessary to send some information to an activity initiated through action _send, which is determined by the target activity to whom it should be sent, such as social apps or apps that send mail.

You can pass the action as a parameter into the intent constructor or the Setaction () method.
To define an action in your own component, you should prefix it with the app's package name, such as:

staticfinal"com.example.action.TIMETRAVEL";
    • Data: A URI object is the representation of a referenced data, or the MIME type of data, and the type of data is determined by intent's action, for example, if action is Action_edit, Then the URI of data should point to an editable file. When creating a intent, in addition to specifying a URI for data, you should also specify the MIME type of data, for example, an activity for displaying a picture cannot be used to play music, if you want to start the activity, You need to specify the MIME type of data as "Image/png", "Image/jpeg", and so on. In some cases, the MIME type can be inferred from the data URI, such as when a URI schema is "content://", indicating that the URI points to a file inside the device and is managed by ContentProvider. The system can infer the MIME type of data based on the file.
      You can call the SetData () method to set the URI, call the Settype () method to set the MIME type, or call the Setdataandtype () method to set both the URI and the MIME type.

      ! Note: If you need to set both the URI and MIME type, you can only call the Setdataandtype () method, not SetData () and Settype () respectively, because when you call SetData (), the contents of Settype () are first empty. and vice versa (they each nullify the value of the other)

    • Category: is a string that represents additional information for the target component, Most intent do not require category. The following is a vaguely common CATEGORY:

      • category_browsable: Indicates that the target activity can be initiated by a link on the Web page, activity or e-mail information activity.
      • Category_launcher: The target activity is the first activity of the task stack, the revelation activity of the application.

      You can pass the category parameter to the Addcategory () method.

The above parameters (component name, action, data, and category) represent the properties of the intent, which allow the system to filter out the target components that meet the criteria. In addition, intent can also contain the following parameters, unlike the above parameters, which are not used to filter the target components:

    • Extras: Additional information that some intent can carry, stored as key-value pairs. You can use the Putextra () method to pass the key value to the information, or you can put the key value pair information in the bundle object, and then pass the bundle object into the Putextra ().
      The intent class encapsulates a number of standard EXTRA in the form of "extra_*", and if you want to encapsulate your own EXTRA key, use the application's registration as a prefix, such as:
staticfinal"com.example.EXTRA_GIGAWATTS";
    • Flags: This parameter can add metadata (meta-data) for intent, and flag can instruct the system how to start an activity, whether to put the activated activity on the application's task stack, and so on.
Example of an implicit intent (Example implicit intent)

! Note: If the target component of the implicit intent is not met in the system, the app will crash (crash), so it should be judged first in the call to StartActivity ().
The following is an example of starting a "activity that sends information" through an implicit intent:

// Create the text message with a stringIntent sendIntent = new Intent();sendIntent.setAction(Intent.ACTION_SEND);sendIntent.putExtra(Intent.EXTRA_TEXT, textMessage);sendIntent.setType("text/plain");// Verify that the intent will resolve to an activityif (sendIntent.resolveActivity(getPackageManager()) != null) {    startActivity(sendIntent);}

If there is a target component that satisfies intent, the component is started, and if there are multiple target components that satisfy the intent, a list is popped up for selection.

Using the app selector (forcing an app chooser)

As stated above, there may be multiple target components in the system that satisfy the implicit intent, a list is popped up for the user to choose, and sometimes the user wants to launch the same component each time (for example, if the user wants to start the Chrome browser instead of the system's own browser each time), then only tick " No longer ask "option is OK, the next time you start, the list will no longer pop up, and sometimes users need to filter the list of activity each time, such as the activation for sharing activity, the user wants to share to different platform each time, You need to call the Intent.createchooser () method to ensure that the selection list pops up each time, as follows:

Intent sendIntent = new Intent(Intent.ACTION_SEND);...for"Share this photo with"String title = getResources().getString(R.string.chooser_title);// Create intent to show the chooser dialogIntent chooser = Intent.createChooser(sendIntent, title);// Verify the original intent will resolve to at least one activityif (sendIntent.resolveActivity(getPackageManager()) != null) {    startActivity(chooser);}
Receive implicit Intent (receiving an implicit Intent)

By configuring the action, data, and category in the Intent-filter tag in the manifest file, you can set filtering information, and only the filtering information that meets the three label settings above will allow intent to open your application components:

    • Action tag:
      You can match the action parameter in the intent.

    • Data Tags:
      You can match the data parameter (URI address and MIME type) in intent.

    • Category Tags:
      You can match the category parameter in the intent.
      ! Note: If the component needs to be implicitly started, the Category_default must be configured
      To implicitly initiate a shared activity, the target activity is configured as follows:

<activity android:name="shareactivity">    <intent-filter>        <action android:name="Android.intent.action.SEND"/>        <category android:name="Android.intent.category.DEFAULT"/>        <data android:mimetype="Text/plain"/>    </intent-filter></activity>

A intent-filter can contain multiple action, data, category tags.

If the component only wants to start with this app, set the exported property in the component to false.
! Note: To avoid implicit intent matching on your service components, do not configure Intent-filter in the service (service must be explicitly started)

Intent-filter Example (Example filters)

Here is an example of a manifest file for a social app:

<activity android:name="mainactivity">    <!--This activity was the main entry, should appear in app launcher--    <intent-filter>        <action android:name="Android.intent.action.MAIN" />        <category android:name="Android.intent.category.LAUNCHER" />    </intent-filter></activity><activity android:name="shareactivity">    <!--This activity handles the "SEND" actions with text data --    <intent-filter>        <action android:name="Android.intent.action.SEND"/>        <category android:name="Android.intent.category.DEFAULT"/>        <data android:mimetype="Text/plain"/>    </intent-filter>    <!--This activity also handles "SEND" and "send_multiple" with media data --    <intent-filter>        <action android:name="Android.intent.action.SEND"/>        <action android:name="Android.intent.action.SEND_MULTIPLE"/>        <category android:name="Android.intent.category.DEFAULT"/>        <data android:mimetype="application/vnd.google.panorama360+jpg"/>        <data android:mimetype="image/*"/>        <data android:mimetype="video/*"/>    </intent-filter></activity>

An action of "Android.intent.action.MAIN" indicates that the activity is the primary entry for the application and does not require data to be configured.
The category "Android.intent.category.LAUNCHER" indicates that the activity's start icon (configured via the Icon property) should be added to the system's LAUNCHER, and if icon is not configured, The icon under the application tag is used.
The above two attributes should appear in pairs.

If you want to start shareactivity implicitly, you just need to match one intent-filter.

Using Pending Intent (using a Pending Intent)

Pendingintent is a class of packaging intent, mainly used to achieve intent delay start, pendingintent the main use of the occasion:

    • Packaging a notification start-up intent;
    • Wrapping an App Widget's intent (activity initiated by the home button);
    • Wraps a delay-activated activity (such as Alarmmanager).

Activity initiated with Pendingintent does not need to be started with startactivity (), and you should start the corresponding component using the corresponding component method:

    • Start an activity by pendingintent.getactivity ();
    • Start a service with Pendingintent.getservice ();
    • Start a broadcastreceiver by Pendingintent.getbroadcast ();
Parsing Intent (Intent Resolution)

The target component matches the corresponding intent by the following three points:

    • The intent action;
    • The intent data (both URI and data type);
    • The intent category.
Match action (action test)

Intent Filter defines 0 to multiple action tags:

<intent-filter>    <action android:name="android.intent.action.EDIT" />    <action android:name="android.intent.action.VIEW" />    ...</intent-filter>

Intent needs to match one of the action tabs. If there is no action tag in the Intent-filter, the intent does not need an action to match.

Match category (category test)

Intent Filter defines 0 to multiple category labels:

<intent-filter>    <category android:name="android.intent.category.DEFAULT" />    <category android:name="android.intent.category.BROWSABLE" />    ...</intent-filter>

Each category defined in intent needs to match the category label on the Intent-filter, which is not true (the category tag in Intent-filter may be more than the category defined in intent). So regardless of whether the category tag is defined in Intent-filter, intent that do not add category always match the intent-filter.
! Note: In intent that are implicitly started by the startactivity () or Startactivityforresult () method, a Category_default category is automatically added, So if you want your activity to be implicitly bootable, you need to add a Android.intent.category.DEFAULT category tag to the Intent-filter.

Match data (data test)

Intent filter can define 0 to multiple data tags:

<intent-filter>    <data android:mimeType="video/mpeg" android:scheme="http"... />    <data android:mimeType="audio/mpeg" android:scheme="http"... />    ...</intent-filter>

Each data tag can set the mimetype and URI structure, where the URI can be divided into four parts: scheme, host, port, and path, with the following structure:

<scheme>://:<port>/<path>

Like what:

content://com.example.project:200/folder/subfolder/etc

which

    • Scheme for content;
    • Host is com.example.project;
    • Port is 200;
    • Path is folder/subfolder/etc.

Each section is not required to be defined in the Data tab, but there is a linear dependency:

    • If scheme is not specified, the host is ignored;
    • If host is not specified, port is ignored;
    • If neither scheme nor host is specified, path is ignored;

The data added in intent only needs to match the data (URI match) in part of Intent-filter:

    • If filter only defines scheme, the URI of the intent data definition can match as long as it contains the same scheme;
    • If filter only defines scheme and host, the URI of the intent data definition can match as long as it contains the same scheme and host;
    • If filter only defines scheme, host, and Port, the URI of the intent data definition can match as long as it contains the same scheme, host, and Port;

The rules for URI and mimetype types in intent-filter matching intent data are as follows:

    1. If data is not specified in the Intent-filter, the intent with no data added can be matched;
    2. If a URI is specified in the Intent-filter, but no mimetype is specified, the rule matches in the previous paragraph (mimetype should also not be specified in intent);
    3. If MimeType is specified in the Intent-filter and no URI is specified, the component that has the same mimetype specified in the intent and no URI specified is available;
    4. If both MimeType and URIs are specified in Intent-filter, then:
      • Intent added in the mimetype as long as the intent-filter can match a certain mimetype, you can match the mimetype part;
      • The URI added in intent is matched to the URI in the previous paragraph, especially if the scheme of the URI in the intent is specified as content: or file:, Then even if the URI is not defined in the Intent-filter, it can be successfully matched. In other words: A URI that contains content: or file: Always matches a intent-filter that defines only mimetype

Apps for Android official Docs (Intents and Intent Filters)

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.