"Android Essentials" uses intent to pass data between activity

Source: Internet
Author: User
Tags call back

Preface:The previous article to everyone to talk about the use of intent method. How to use intent to activate activity and implicit intent. This article gives you a talk about how to use intent to communicate between activity.


Get the return result from an activity:

Starting an activity is not startactivity (Intent Intent) a method. You can also start an activity with Startactivityforresult () and receive a return result when it exits.

Example. You can call the system camera in your app, take a picture, and then return to your activity, and this way you can return the photo as a result to your activity.

Again, for example. You can use this method to start the system contact app and then get a person's specific contact information.

Note: You can use the display intent or the implicit intent when calling Startactivityforresult (). But when you can use explicit intent, try to use explicit intent. This ensures that the returned result is the correct result you expect.

Start an activity:

When starting an activity with Startactivityforresult (), the intent is the same as startactivity (), no matter what the difference. It's just that you need to pass an extra integer variable as the starting parameter. When the activated activity exits, the parameter is used as a reference to the callback function to distinguish the returned result. This means that the number of participants (Requestcode) that you pass when you start the activity is the same as the one that was returned (Requestcode).

Here is a sample that calls Startactivityforresult () to get a contact:

static final int pick_contact_request = 1; The request code ... private void Pickcontact () {Intent pickcontactintent = new Intent (Intent.action_pick, Uri.pars    E ("content://contacts")); Pickcontactintent.settype (Phone.content_type); Show user only contacts W/phone numbers Startactivityforresult (pickcontactintent, pick_contact_request);}

The Startactivityforresult () function is this in the activity source code:

/** * Same as calling {@link #startActivityForResult (Intent, int, Bundle)} * with no options.     * * @param intent the intent to start. * @param requestcode If >= 0, this code would be returned in * Onactivityresult () when the Activi     Ty exits. * * @throws android.content.ActivityNotFoundException * * @see #startActivity */public void Startactiv    Ityforresult (Intent Intent, int requestcode) {Startactivityforresult (Intent, requestcode, NULL); }
This method is overloaded in activity. Startactivityforresult (Intent, requestcode, null); The method is not posted.

However, for the use of this method of precautions I would like to translate for you:

    • This method can only be used to start a activity,intent with the return result of the parameter setting needs to be noted. You can't start an activity using Singletask's launch mode, start the activity with Singletask, the activity in another activity stack, you'll receive result_ immediately. Canceled message.
    • You cannot call the Startactivityforresult () method before the activity life cycle function onresume, assuming that you have called before Onresume. The activity cannot be displayed until the activity that is started exits and returns the result, in order to avoid flashing the form again when directed to another activity;

Receive returned results:

When Startactivityforresult () starts the activity completion task exits, the system will call back the Onactivityresult () method that you called the activity. This method has three parameters:

    • Resquestcode: The requestcode that is passed when the activity is started.
    • ResultCode: A variable that represents a successful or failed invocation, with a value of one of the following;/** standard activity result:operation canceled.    */public static final int result_canceled = 0; /** standard activity result:operation succeeded. */public static final int result_ok =-1;
    • Intent: Includes Intent to return content;
The following code is a sample that handles getting a contact result:
@Override  protected void Onactivityresult (int requestcode, int resultcode, Intent data) {   //Check which Request we ' re responding to     if (Requestcode = = pick_contact_request) {       //M Ake sure the request was successful         if (ResultCode = = RESULT_OK) {      &N Bsp    //The user picked a contact.            //The Intent ' s data Uri identi Fies which contact is selected.             //do something with the E (bigger example below)         }    } }
Note: In order to properly handle the returned intent results, you need to understand clearly the format of the intent return results. Suppose you write your own intent as the return result you will be very clear, but suppose it is called the System app (camera. Contacts, etc.), then intent returns the result format you should know clearly.

For example: The Contact app is the return contacts URI. The camera returns the bitmap data.


Handling returned results: The following code deals with the results of getting contacts:
@Override  protected void Onactivityresult (int requestcode, int resultcode, Intent data) {   //Check which Request it is that we ' re responding to     if (Requestcode = = pick_contact_request) {       /Make sure the request is successful         if (ResultCode = = RESULT_OK) {  &nbsp ;        //Get the URI that points to the selected contact           &NB Sp  Uri Contacturi = Data.getdata ();           //We only need the number column, because there Would be is only one row in the result             string[] projection = {PHONE.NUMBER};&N bsp;           //Perform the query on the contact to get the number column   &NB Sp        //We don ' t need a selection or sort order (there ' s only one result for the given URI)  &N Bsp   &NBsp      //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.     &N Bsp       CURSOR cursor = Getcontentresolver ()                   &N BSP;. query (Contacturi, projection, NULL, NULL, NULL);            Cursor.movetofirst (); &nbs p;           //Retrieve the phone number from the number column             INT column = Cursor.getcolumnindex (phone.number);            String num ber = cursor.getstring (column);            //do something with the phone NUMBER...&NB sp;    &NBsp  }    } }
The following code is the result of processing the calling system camera return:
@Override protected void Onactivityresult (int requestcode, int resultcode, Intent data) {if (Requestcode = = Request_im        Age_capture && ResultCode = = result_ok) {Bundle extras = Data.getextras ();        Bitmap Imagebitmap = (Bitmap) extras.get ("Data");    Mimageview.setimagebitmap (IMAGEBITMAP); } }
Get Startup intent:

In the activity that is being activated you can receive the intent that initiates the activity, which can be called getintent () within the life cycle to obtain the intent, However, they are generally obtained in the oncreat and OnStart functions. Here's an example of getting intent:

@Override protected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);     Setcontentview (R.layout.main);    Get the intent that started this activity intent intent = getintent ();     Uri data = Intent.getdata (); Figure out how to does based on the intent type if (Intent.gettype (). IndexOf ("image/")! =-1) {//Handle int Ents with image data ...} else if (Intent.gettype (). Equals ("Text/plain")) {//Handle intents with text ...}}
Set the return intent:

The above describes how to handle intent in Onactivityresult (). But how to set this return intent in your app? Suppose you want to return a result to your activity that invokes Setresult () to set the return content, and then end the activity.

The following code is a demo sample:

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

The above is the use of intent in different activity for information transmission and communication of the commentary, to this intent series of articles end. The first two articles are about intent specific explanations and intent use. What is unclear, please leave a message, we learn together. Progress together, thank you.

Everyone assumes that you are interested in programming, want to know a lot of other programming knowledge, solve programming problems, want to learn a certain kind of development knowledge, we have Java master here. C++/C Master, Windows/linux Master, Android/ios Master, please pay attention to my public number: Program Ape Interactive Alliance or Coder_online. Daniel is on-line to provide you with services.

Android Foundation uses intent to pass data between activity

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.