这是我从 Fragment 中获取联系人照片、号码和姓名的方法。
1 在你的清单文件中设置权限。
<uses-permission android:name="android.permission.READ_CONTACTS" />
2 声明一个常量:
private static final int REQUEST_CODE_PICK_CONTACT = 1;
3 在我的应用程序中,用户需要通过点击按钮选择电话联系人。因此,在onClick()方法中,我这样做:
contactChooserButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
startActivityForResult(new Intent(Intent.ACTION_PICK,
ContactsContract.Contacts.CONTENT_URI), REQUEST_CODE_PICK_CONTACT);
}
});
4 添加获取照片、姓名和号码的方法:
private String retrieveContactNumber() {
String contactNumber = null;
Cursor cursorID = getActivity().getContentResolver().query(uriContact,
new String[]{ContactsContract.Contacts._ID},
null, null, null);
if (cursorID.moveToFirst()) {
contactID = cursorID.getString(cursorID.getColumnIndex(ContactsContract.Contacts._ID));
}
cursorID.close();
Log.e(TAG, "Contact ID: " + contactID);
Cursor cursorPhone = getActivity().getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
new String[]{ContactsContract.CommonDataKinds.Phone.NUMBER},
ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ? AND " +
ContactsContract.CommonDataKinds.Phone.TYPE + " = " +
ContactsContract.CommonDataKinds.Phone.TYPE_MOBILE,
new String[]{contactID},
null);
if (cursorPhone.moveToFirst()) {
contactNumber = cursorPhone.getString(cursorPhone.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
phoneNumber = contactNumber;
}
cursorPhone.close();
Log.e(TAG, "Contact Phone Number: " + contactNumber);
return contactNumber;
}
private void retrieveContactName() {
String contactName = null;
Cursor cursor = getActivity().getContentResolver().query(uriContact, null, null, null, null);
if (cursor.moveToFirst()) {
contactName = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
personName = contactName;
}
cursor.close();
Log.e(TAG, "Contact Name: " + contactName);
}
public void retrieveContactPhoto() {
Uri contactUri = ContentUris.withAppendedId(ContactsContract.Contacts.CONTENT_URI, Long.parseLong(contactID));
Uri displayPhotoUri = Uri.withAppendedPath(contactUri, ContactsContract.Contacts.Photo.DISPLAY_PHOTO);
try {
AssetFileDescriptor fd =
getActivity().getContentResolver().openAssetFileDescriptor(displayPhotoUri, "r");
photoAsBitmap = BitmapFactory.decodeStream(fd.createInputStream());
} catch (IOException e) {
e.printStackTrace();
}
}
最后,在你的onActivityForResult方法中,做这个:
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
try {
if(requestCode == REQUEST_CODE_PICK_CONTACT && resultCode == Activity.RESULT_OK) {
Log.e(TAG, "Response: " + data.toString());
uriContact = data.getData();
personPhoneTextField.setText(retrieveContactNumber());
retrieveContactPhoto();
retrieveContactName();
}
} catch (Exception exception) {
exception.printStackTrace();
}
}
就这样了。关于活动,请查看Github上的Android:获取联系人详细信息(ID、姓名、电话、照片)。