Interactive------Intent for Android Apps

Source: Internet
Author: User

To allow users to jump from one activity to another, our app must use intent to define its intentions. When using the StartActivity () method and the parameter is Intent, the system uses this Intent to define and launch the appropriate app component. Using intents can even let the app launch activity in another app.

Activity, service, and broadcastreceiver are activated through the intent mechanism, while different types of components have different ways of passing intent.

I. Components of the intent
    • The component property needs to accept a ComponentName object, componentname need to specify the package name and class name, which uniquely identifies a component class so that the application can start a particular component based on the given component.
    • Both the Action property and the category property are common strings, where the action represents an abstract "action" to be done by the intent, and the category is used to add additional additional category information to the action. The Action property is typically used in conjunction with the Category property.
    • The data property is typically used to provide the Action property with the information of the operation. The Data property accepts a URI object, and the URI string always satisfies the following format: Scheme://host:port/path
    • The Type property is used to specify the MIME type for the URI specified by the data, which can be any custom MIME type, as long as the string conforms to the ABC/XYZ format.
    • The extra property is typically used to exchange data between multiple actions, and intent's extra property value should be a bundle object.
    • The Flag property is used to add some additional control flags to the intent
Two. Call method for Intent 1. Display (Explicit) call

Explicit intent need to explicitly specify the class name of the component to start or trigger

  

2. Implicit (implicit) call

Implicit intent only specifies what conditions should be met by the component that needs to be started or triggered. For an implicit intent, the Android system needs to parse the intent, parse out its conditions, and then go to the system to find the target component that matches it. If a component that meets the criteria is found, they are started or triggered.

Implicit intents does not declare the specific class name of the component to start, but rather declares an action that needs to be executed. This action specifies what we want to do, such as viewing, editing, sending, or getting something. Intents usually comes with some data when you send an action, such as the address you want to view or the message you want to send. The exact type of data depends on the intent we want to create, such as URLs or other defined data types, or even the need for data at all.

For example:

Call Uri number = Uri.parse ("tel:5551234"); Intent callintent = new Intent (intent.action_dial, number);//view map/maps point B ased on Addressuri location = Uri.parse ("Geo:0,0?q=1600+amphitheatre+parkway,+mountain+view,+california");//Or map Point based to latitude/longitude//Uri location = Uri.parse ("geo:37.422219,-122.08364?z=14"); Z param is zoom levelintent mapintent = new Intent (Intent.action_view, location);//Open Web page Uri webpage = uri.parse ("http:// Www.android.com "); Intent webintent = new Intent (Intent.action_view, webpage);

  Some implicit intent that require additional data, we can use the Putextra () method to add some data. If we do not include a URI in intent, we usually need to use the SetType () method to specify the data type that is included with the intent. The MIME type is set to specify that the activity of this intent should be accepted.

Send a emailintent with an attachment emailintent = new Intent (intent.action_send);//The Intent does not having a URI, so declare the "text /plain "MIME typeemailintent.settype (HTTP. Plain_text_type); Emailintent.putextra (Intent.extra_email, new string[] {"[email protected]"}); Recipientsemailintent.putextra (Intent.extra_subject, "Email SUBJECT"); Emailintent.putextra (Intent.extra_text, " Email message text "); Emailintent.putextra (Intent.extra_stream, Uri.parse (" content://path/to/email/attachment ")); /You can also attach multiple items to passing an ArrayList of uris//create a calendar event: Intent calendarintent = new Intent (intent.a Ction_insert, Events.content_uri); Calendar beginTime = Calendar.getinstance (). Set (2012, 0, 19, 7, 30); Calendar endTime = Calendar.getinstance (). Set (0, N, ten, +); Calendarintent.putextra (Calendarcontract.extra_ Event_begin_time, Begintime.gettimeinmillis ()); Calendarintent.putextra (Calendarcontract.extra_event_end_time, Endtime.gettimeinmillis ()); Calendarintent.putextra (events.titLE, "Ninja class"); Calendarintent.putextra (Events.event_location, "Secret Dojo"); 

Verify that you have an app to receive this intent:

  intent will be received by one of the system's built-in apps (such as the Phone, Email, or Calendar app). To verify that a suitable activity responds to this intent, you need to perform queryintentactivities ()   to get a list of all the activity that can receive this intent. If the returned list non-empty, then we can safely use this intent. For example:

Packagemanager Packagemanager = Getpackagemanager (); List<resolveinfo> activities = packagemanager.queryintentactivities (intent, 0); Boolean isintentsafe = Activities.size () > 0;

Display the sharing app's selection screen

  Note that when a intent is passed as startactivity () and multiple apps can be handle, the user can select the app that launches by default when the dialog pops up (by ticking the box below dialog, as shown). This feature is useful when a user has a special preference (for example, a user always likes to start an app to view a webpage, and always likes to start a camera to take a photo).

  in order to display multiple open methods, you need to use Createchooser () to create a intent:

Intent Intent = new Intent (intent.action_send) ...//Always use string resources for UI text. This says something like "Share this photo with" String title = Getresources (). GetText (R.string.chooser_title);//Create an D start the Chooserintent chooser = Intent.createchooser (Intent, title); StartActivity (chooser);
Three. Receive the results returned by activity

Starting another activity is not necessarily one-way. We can also start another activity and accept a return result. To accept result, we need to use the startactivityforresult () &NBSP; instead of startactivity () .

Of course, the activated activity needs to specify the return result. It needs to return this result as another intent object, and our activity needs to be in onactivityresult () The callback method inside to receive result.

  The intent in the Startactivityforresult () method is not much different from what was described earlier, but it is necessary to add an int type parameter to this method.

This integer parameter is called "Request Code" and is used to identify the request. When we receive the result intent, we can judge whether this result is what we want from the parameters inside the callback method.

Start activitystatic Final int pick_contact_request = 1; The request code...private void Pickcontact () {Intent pickcontactintent = new Intent (Intent.action_pick, Uri.parse (    "Content://contacts")); Pickcontactintent.settype (Phone.content_type); Show user only contacts W/phone numbers Startactivityforresult (pickcontactintent, pick_contact_request);} Receive result/* when the user completes the activity operation after the start, the system invokes the Onactivityresult () callback method in our activity. The method has three parameters: request code passed through Startactivityforresult (). The second activity specifies the result code. If the operation succeeds is RESULT_OK, if the user does not succeed, but instead directly click fallback or some other reason, then the result_canceled contains the returned result data intent.  */@Overrideprotected void onactivityresult (int requestcode, int resultcode, Intent data) {//Check which request we ' re Responding to if (Requestcode = = pick_contact_request) {//Make sure the REQUEST is successful if (res            Ultcode = = RESULT_OK) {//the user picked a contact.            The Intent ' s data Uri identifies which contact is selected.Do something with the contact here (bigger example below)}} 

  the activity that handles intent returns result only needs to be executed Setresult (), by specifying a result code with result intent. After the operation is completed, the user needs to return to the original activity and close the aroused activity by executing finish ().

Create intent to deliver some kind of result dataintent result = new Intent ("Com.example.RESULT_ACTION", Uri.parse ("Con Tent://result_uri "); Setresult (ACTIVITY.RESULT_OK, result); finish ();

   the value of result code is usuallyRESULT_OK或RESULT_CANCELED(默认)。if you simply want to return an int to represent one of the returned result data, you can set the result code to any value greater than 0. If the result we return is just an int, then even the intent can be returned without having to return it and can callsetResult()。

Setresult (result_color_red); finish ();

Four. Intent Filter

by manifest in <activity> file; tags Add < Intent-fliter > properties so that other apps can start our activity.

In order to define as precisely as possible the intent that activity can handle, each intent filter should define action and data as thoroughly as possible.

  • Action : The name of an action that you want to perform. Usually the system has defined values such as action_send or action_view . In intent filter through <ACTION> specifies its value, the type of the value must be a string, not a constant in the API (see example below)

  • Data : Intent a description of the accompanying data. In intent filter through <DATA> Specifies its value, you can use one or more properties, we can define only the MIME type or only specify the URI prefix, You can also define only one URI scheme, or they may be used in combination.

    • 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 seldom used. Moreover, all implicit intents are the Category_default type by default. In intent filter, use <CATEGORY> specifies its value.
<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>

Interactive------Intent for Android Apps

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.