[Android Basics] uses Intent to transmit data between activities, androidintent

Source: Internet
Author: User

[Android Basics] uses Intent to transmit data between activities, androidintent
Preface:In the previous article, we talked about Intent usage, how to use Intent to start Activity and implicit Intent. This article will show you how to use Intent to communicate between activities. Get the returned result from an Activity:

Starting an Activity is not just a startActivity (Intent intent) method. You can also start an Activity by startActivityForResult () and receive a returned result when it exits.

For example, you can call the System camera to take a photo in your application and then return it to your Activity, in this way, you can return the photo as a result to your Activity. For example, you can use this method to start the system Contact application and obtain the contact details of a person.

Note: When startActivityForResult () is called, you can use the Intent or implicit Intent display, but try to use the explicit Intent when using the explicit Intent, this ensures that the returned results are the correct ones you expect.
Start an Activity:

When startActivityForResult () is used to start an Activity, Intent is written in the same way as startActivity (). There is no difference, but you need to pass an extra Integer variable as the startup parameter, when the started Activity exits, this parameter will be used as a parameter of the callback function to differentiate the returned results. That is to say, the parameter (requestCode) You passed when starting the Activity) the parameter (requestCode) is the same as that of the returned result.

The following is an example of calling startActivityForResult () to obtain a contact:

static 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);}

  

The startActivityForResult () function is like 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 will be returned in     *                    onActivityResult() when the activity exits.     *     * @throws android.content.ActivityNotFoundException     *     * @see #startActivity     */    public void startActivityForResult(Intent intent, int requestCode) {        startActivityForResult(intent, requestCode, null);    }

  

This method is overloaded in the Activity. startActivityForResult (intent, requestCode, null); the method will not be pasted. However, I will translate the notes for using this method:
  • This method can only be used to start an Activity with returned results. Please note that you cannot start an Activity with the launch mode of singleTask and start the Activity with singleTask, the Activity is in another Activity stack, and you will immediately receive the RESULT_CANCELED message;
  • The startActivityForResult () method cannot be called before the Activity Life Cycle Function onResume. If you call the startActivityForResult () method before onResume, the Activity in which the Activity is located cannot be displayed until the started Activity exits and the result is returned, this is to avoid window flickering when redirecting to another Activity;
Receive returned results:

When the Activity started by startActivityForResult () Exits after the task is completed, the system calls you to call the onActivityResult () method of the Activity. This method has three parameters:

  • ResquestCode: The requestCode passed when the Activity is started;
  • ResultCode: a variable indicating a successful or failed call. The value is either 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: contains the Intent of the returned content;
The following code is an example of how to obtain the contact result:
@Override protected void onActivityResult(int requestCode, int resultCode, Intent data) {    // Check which request we're responding to     if (requestCode == PICK_CONTACT_REQUEST) {        // Make sure the request was successful         if (resultCode == RESULT_OK) {            // The user picked a contact.             // The Intent's data Uri identifies which contact was selected.              // Do something with the contact here (bigger example below)         }     } }

  

Note: To correctly process returned Intent results, you need to understand the format of Intent returned results. If you write your own Intent as the returned result, you will be very clear, but if it is the called system APP (camera, contact, etc.), then you should be clear about the Intent returned result format. For example, the Contact application returns the contact URI and the camera returns Bitmap data.
Processing returned results: the following code processes the results of obtaining 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 was successful         if (resultCode == RESULT_OK) {            // Get the URI that points to the selected contact             Uri contactUri = data.getData();            // We only need the NUMBER column, because there will be only one row in the result             String[] 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 be called from a separate thread to avoid blocking             // your app's UI thread. (For simplicity of the sample, this code doesn't do 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             int column = cursor.getColumnIndex(Phone.NUMBER);            String number = cursor.getString(column);             // Do something with the phone number...         }     } }

  

The following code processes the results returned by calling the System camera:
@Override protected void onActivityResult(int requestCode, int resultCode, Intent data) {    if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {        Bundle extras = data.getExtras();        Bitmap imageBitmap = (Bitmap) extras.get("data");        mImageView.setImageBitmap(imageBitmap);    } }

  

Get start Intent:

In the started Activity, you can receive the Intent that starts the Activity and call getIntent () within the lifecycle to obtain the Intent, however, it is generally obtained in the onCreat and onStart functions. The following is 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 what to do based on the intent type     if (intent.getType().indexOf("image/") != -1) {        // Handle intents with image data ...     } else if (intent.getType().equals("text/plain")) {        // Handle intents with text ...     } }

  

Set the returned Intent:

This article describes how to process Intent in onActivityResult (), but how to set this returned Intent in your application? If you want to return a result to your Activity, you can set the returned content by calling setResult () and end the Activity. The following code is an example:

// Create intent to deliver some kind of result data Intent result = new Intent("com.example.RESULT_ACTION", Uri.parse("content://result_uri");setResult(Activity.RESULT_OK, result);finish();

  

The above is the description of information transmission and communication using Intent in different activities. By the end of this Intent series, the first two articles are about Intent details and Intent usage, if you have any questions, please leave a message. You can learn and make progress together. Thank you!

If you are interested in programming, want to learn more about programming, solve programming problems, and want the system to learn a certain kind of development knowledge, we have a master of java here, C ++/C master, windows/Linux master, android/ios Master, please pay attention to my public account: programmer InterAction alliance or coder_online, and Daniel online provides services for you.

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.