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