"Android App Development technology: Application Components" intent how to use

Source: Internet
Author: User

Guo Xiaoxing
Weibo: Guo Xiaoxing's Sina Weibo
Email:[email protected]
Blog: http://blog.csdn.net/allenwells
Github:https://github.com/allenwells

One Intent verification

Although the Android system will ensure that every identified intent is received by one of the system's built-in apps (such as the Phone, Email, or Calendar app), But we should also verify that the app accepts this intent step before triggering a intent, because if we trigger a intent and none of the apps will receive the intent, our app crashes.

To verify that the appropriate activity responds to this intent, you need to execute queryintentactivities () to get a list of all the activity that can receive the intent. If the returned list is not empty, then we can safely use this intent, as follows:

PackageManager packageManager = getPackageManager();List<ResolveInfo> activities = packageManager.queryIntentActivities0);boolean isIntentSafe = activities.size0;

When we created the intent and set up the extra data, we sent it to the system by executing startactivity (intent). If the system determines that more than one activity can handle this intent, it will show a dialog that lets the user choose which app to launch. If the system discovers that only one app can handle this intent, it will start the app directly, as shown here:

Example

Create a intent to view the map, verify that an app can handle the intent, and then launch it.

// Build the intentUri location = Uri.parse("geo:0,0?q=1600+Amphitheatre+Parkway,+Mountain+View,+California"new Intent(Intent.ACTION_VIEW, location);// Verify it resolves0);boolean0;// Start an activity if it‘s safeif (isIntentSafe) {    startActivity(mapIntent);}
Two intent Send (1) Start activity

Starting another activity is not necessarily one-way. We can also start another activity and accept a result back. In order to receive this result, we need to use Startactivityforresult () instead of startactivity (), as follows:

Example

Start Activity to select contacts

staticfinalint1;  // The request code...privatevoidpickContact() {    newnew Uri("content://contacts"));    // Show user only contacts w/ phone numbers    startActivityForResult(pickContactIntent, PICK_CONTACT_REQUEST);}
(2) Receive result

The Onactivityresult () callback method of your activity is called after the user has completed the activity operation after startup. This method has three parameters, as follows:

    • The first request code passed through Startactivityforresult ().
    • The second activity specifies the result code. If the operation is successful, it is RESULT_OK, if the user does not succeed, but the direct click fallback or some other reason, then it is result_canceled.
    • The third parameter is intent, which contains the result data portion of the return.

Example

Process select contacts to return results.

@Overrideprotected void Onactivityresult(intRequestcode,intResultCode, Intent data) {//Check which request it is, we ' re responding to    if(Requestcode = = pick_contact_request) {//Make sure the request was successful        if(ResultCode = = RESULT_OK) {//Get The URI that is points to the selected contactUri Contacturi = Data.getdata ();//We only need the number column, because there would be is only one row in the resultstring[] projection = {Phone.number};//Perform the query on the contact to get the number column            //We don ' t need a selection or sort order (there ' s only one result for the given URI)            //Caution:the query () method should is called from a separate thread to avoid blocking            //Your app ' s UI thread. (For simplicity of the sample, this code doesn ' t does that.)            //Consider using Cursorloader to perform the query.cursor cursor = getcontentresolver (). Query (Contacturi, projection,NULL,NULL,NULL); Cursor.movetofirst ();//Retrieve The phone number from the number column            intColumn = Cursor.getcolumnindex (phone.number); String number = cursor.getstring (column);//Do something with the phone number ...}    }}
Tri-Intent Filtration

To define as precisely as possible which intent the activity can handle, each intent filter should define action and data as thoroughly as possible. If the intent filter in the activity satisfies the criteria of the following intent object, the system is able to send a specific intent to the activity, as follows:

    • Action: The name of the action you want to perform. This is usually a value that the system has already defined, such as Action_send or Action_view. In Intent Filt
      With the value specified for it, the type of the value must be a string, not a constant in the API.
    • Data:intent a description of the accompanying data. In intent filter, you can use one or more properties to specify its value, you can define only the MIME type or only the URI prefix, or you can define only one URI Scheme, or they may be used in combination.
    • Note: If you do not want to handle data for the URI type, then we should specify the Android:mimetype property. such as Text/plain or Image/jpeg.
    • Category: Provides an additional way to identify the intent that the activity can handle. This is usually related to the user's gesture or the start position. The system supports several different categories, but most of them are not very helpful. Moreover, all implicit intents are the Category_default type by default. Specify its value in the intent filter.

In intent filter, we can define the corresponding XML element in the element to declare what criteria the activity uses.

Example

The intent of action_send is processed when the data type is text or an image.

<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"/>        <data android:mimetype="image/*"/>    </intent-filter></activity>

Each sent intent will only contain an action and data type, but handle this intent activity can be declared multiple, with. If any of the two pairs of action and data are contradictory, we should create a different intent filter to specify a specific action and type.

Example

Activity can handle text and pictures, whether action_send or action_sendto intent. In this case, we need to define two different intent Filter for two action. Because the Action_sendto intent must use the URI type to specify the recipient to use the address of send or sendto, as follows:

<activity android:name="shareactivity">    <!--filter for sending text, accepts SENDTO action with SMS URI schemes --    <intent-filter>        <action android:name="Android.intent.action.SENDTO"/>        <category android:name="Android.intent.category.DEFAULT"/>        <data android:scheme="sms" />        <data android:scheme="Smsto" />    </intent-filter>    <!--filter for sending text or images; accepts SEND action and text or image data --    <intent-filter>        <action android:name="Android.intent.action.SEND"/>        <category android:name="Android.intent.category.DEFAULT"/>        <data android:mimetype="image/*"/>        <data android:mimetype="Text/plain"/>    </intent-filter></activity>

Note : In order to receive intent, we need to include the category of Category_default in the intent filter. The StartActivity () and Startactivityforresult () methods treat all intent as declaring the Category_default category. If Category_default is not declared in the intent filter, then activity will not respond to the implicit intent.

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

"Android App Development technology: Application Components" intent how to use

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.