Home | History | Annotate | Download | only in intents
      1 page.title=Getting a Result from an Activity
      2 parent.title=Interacting with Other Apps
      3 parent.link=index.html
      4 
      5 trainingnavtop=true
      6 previous.title=Sending the User to Another App
      7 previous.link=sending.html
      8 next.title=Allowing Other Apps to Start Your Activity
      9 next.link=filters.html
     10 
     11 @jd:body
     12 
     13 <div id="tb-wrapper">
     14   <div id="tb">
     15 
     16 <h2>This lesson teaches you to</h2>
     17 <ol>
     18   <li><a href="#StartActivity">Start the Activity</a></li>
     19   <li><a href="#ReceiveResult">Receive the Result</a></li>
     20 </ol>
     21 
     22 <h2>You should also read</h2>
     23 <ul>
     24     <li><a href="{@docRoot}training/sharing/index.html">Sharing Simple Data</a></li>
     25     <li><a href="{@docRoot}training/secure-file-sharing/index.html">Sharing Files</a>
     26 </ul>
     27 
     28   </div>
     29 </div>
     30 
     31 <p>Starting another activity doesn't have to be one-way. You can also start another activity and
     32 receive a result back. To receive a result, call {@link android.app.Activity#startActivityForResult
     33 startActivityForResult()} (instead of {@link android.app.Activity#startActivity
     34 startActivity()}).</p>
     35 
     36 <p>For example, your app can start a camera app and receive the captured photo as a result. Or, you
     37 might start the People app in order for the user to select a
     38 contact and you'll receive the contact details as a result.</p>
     39 
     40 <p>Of course, the activity that responds must be designed to return a result. When it does, it
     41 sends the result as another {@link android.content.Intent} object. Your activity receives it in
     42 the {@link android.app.Activity#onActivityResult onActivityResult()} callback.</p>
     43 
     44 <p class="note"><strong>Note:</strong> You can use explicit or implicit intents when you call
     45 {@link android.app.Activity#startActivityForResult startActivityForResult()}. When starting one of
     46 your own activities to receive a result, you should use an explicit intent to ensure that you
     47 receive the expected result.</p>
     48 
     49 
     50 <h2 id="StartActivity">Start the Activity</h2>
     51 
     52 <p>There's nothing special about the {@link android.content.Intent} object you use when starting
     53 an activity for a result, but you do need to pass an additional integer argument to the {@link
     54 android.app.Activity#startActivityForResult startActivityForResult()} method.</p>
     55 
     56 <p>The integer argument is a "request code" that identifies your request. When you receive the
     57 result {@link android.content.Intent}, the callback provides the same request code so that your
     58 app can properly identify the result and determine how to handle it.</p>
     59 
     60 <p>For example, here's how to start an activity that allows the user to pick a contact:</p>
     61 
     62 <pre>
     63 static final int PICK_CONTACT_REQUEST = 1;  // The request code
     64 ...
     65 private void pickContact() {
     66     Intent pickContactIntent = new Intent(Intent.ACTION_PICK, Uri.parse("content://contacts"));
     67     pickContactIntent.setType(Phone.CONTENT_TYPE); // Show user only contacts w/ phone numbers
     68     startActivityForResult(pickContactIntent, PICK_CONTACT_REQUEST);
     69 }
     70 </pre>
     71 
     72 
     73 <h2 id="ReceiveResult">Receive the Result</h2>
     74 
     75 <p>When the user is done with the subsequent activity and returns, the system calls your activity's
     76 {@link android.app.Activity#onActivityResult onActivityResult()} method. This method includes three
     77 arguments:</p>
     78 
     79 <ul>
     80   <li>The request code you passed to {@link
     81 android.app.Activity#startActivityForResult startActivityForResult()}.</li>
     82   <li>A result code specified by the second activity. This is either {@link
     83 android.app.Activity#RESULT_OK} if the operation was successful or {@link
     84 android.app.Activity#RESULT_CANCELED} if the user backed out or the operation failed for some
     85 reason.</li>
     86   <li>An {@link android.content.Intent} that carries the result data.</li>
     87 </ul>
     88 
     89 <p>For example, here's how you can handle the result for the "pick a contact" intent:</p>
     90 
     91 <pre>
     92 &#64;Override
     93 protected void onActivityResult(int requestCode, int resultCode, Intent data) {
     94     // Check which request we're responding to
     95     if (requestCode == PICK_CONTACT_REQUEST) {
     96         // Make sure the request was successful
     97         if (resultCode == RESULT_OK) {
     98             // The user picked a contact.
     99             // The Intent's data Uri identifies which contact was selected.
    100 
    101             // Do something with the contact here (bigger example below)
    102         }
    103     }
    104 }
    105 </pre>
    106 
    107 <p>In this example, the result {@link android.content.Intent} returned by
    108 Android's Contacts or People app provides a content {@link android.net.Uri} that identifies the
    109 contact the user selected.</p>
    110 
    111 <p>In order to successfully handle the result, you must understand what the format of the result
    112 {@link android.content.Intent} will be. Doing so is easy when the activity returning a result is
    113 one of your own activities. Apps included with the Android platform offer their own APIs that
    114 you can count on for specific result data. For instance, the People app (Contacts app on some older
    115 versions) always returns a result with the content URI that identifies the selected contact, and the
    116 Camera app returns a {@link android.graphics.Bitmap} in the {@code "data"} extra (see the class
    117 about <a href="{@docRoot}training/camera/index.html">Capturing Photos</a>).</p>
    118 
    119 
    120 <h4>Bonus: Read the contact data</h4>
    121 
    122 <p>The code above showing how to get a result from the People app doesn't go into
    123 details about how to actually read the data from the result, because it requires more advanced
    124 discussion about <a href="{@docRoot}guide/topics/providers/content-providers.html">content
    125 providers</a>. However, if you're curious, here's some more code that shows how to query the
    126 result data to get the phone number from the selected contact:</p>
    127 
    128 <pre>
    129 &#64;Override
    130 protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    131     // Check which request it is that we're responding to
    132     if (requestCode == PICK_CONTACT_REQUEST) {
    133         // Make sure the request was successful
    134         if (resultCode == RESULT_OK) {
    135             // Get the URI that points to the selected contact
    136             Uri contactUri = data.getData();
    137             // We only need the NUMBER column, because there will be only one row in the result
    138             String[] projection = {Phone.NUMBER};
    139 
    140             // Perform the query on the contact to get the NUMBER column
    141             // We don't need a selection or sort order (there's only one result for the given URI)
    142             // CAUTION: The query() method should be called from a separate thread to avoid blocking
    143             // your app's UI thread. (For simplicity of the sample, this code doesn't do that.)
    144             // Consider using {@link android.content.CursorLoader} to perform the query.
    145             Cursor cursor = getContentResolver()
    146                     .query(contactUri, projection, null, null, null);
    147             cursor.moveToFirst();
    148 
    149             // Retrieve the phone number from the NUMBER column
    150             int column = cursor.getColumnIndex(Phone.NUMBER);
    151             String number = cursor.getString(column);
    152 
    153             // Do something with the phone number...
    154         }
    155     }
    156 }
    157 </pre>
    158 
    159 <p class="note"><strong>Note:</strong> Before Android 2.3 (API level 9), performing a query
    160 on the {@link android.provider.ContactsContract.Contacts Contacts Provider} (like the one shown
    161 above) requires that your app declare the {@link
    162 android.Manifest.permission#READ_CONTACTS} permission (see <a
    163 href="{@docRoot}guide/topics/security/security.html">Security and Permissions</a>). However,
    164 beginning with Android 2.3, the Contacts/People app grants your app a temporary
    165 permission to read from the Contacts Provider when it returns you a result. The temporary permission
    166 applies only to the specific contact requested, so you cannot query a contact other than the one
    167 specified by the intent's {@link android.net.Uri}, unless you do declare the {@link
    168 android.Manifest.permission#READ_CONTACTS} permission.</p>
    169 
    170 
    171 
    172 
    173 
    174 
    175 
    176 
    177 
    178 
    179 
    180 
    181 
    182 
    183 
    184