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);
}
@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)
}
}
}
本例中被返回的Intent使用Uri的形式來表示返回的聯(lián)系人。
為正確處理這些result,我們必須了解那些result intent的格式。對(duì)于自己程序里面的返回result是比較簡(jiǎn)單的。Apps都會(huì)有一些自己的api來指定特定的數(shù)據(jù)。例如,People app (Contacts app on some older versions) 總是返回一個(gè)URI來指定選擇的contact,Camera app 則是在data數(shù)據(jù)區(qū)返回一個(gè) Bitmap (see the class about Capturing Photos).
@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...
}
}
}
Note:在Android 2.3 (API level 9)之前對(duì)Contacts Provider的請(qǐng)求(比如上面的代碼),需要聲明READ_CONTACTS權(quán)限(更多詳見Security and Permissions)。但如果是Android 2.3以上的系統(tǒng)就不需要這么做。但這種臨時(shí)權(quán)限也僅限于特定的請(qǐng)求,所以仍無法獲取除返回的Intent以外的聯(lián)系人信息,除非聲明了READ_CONTACTS權(quán)限。
更多建議: