不能保证这适用于4.0,因为我有一段时间没有使用它,但在2.3.3上工作正常:
要获取contactId,我首先让用户选择一个联系人:
public void clickSelectContact(View v) {
Intent i = new Intent(Intent.ACTION_PICK, ContactsContract.CommonDataKinds.Phone.CONTENT_URI);
startActivityForResult(i, CONTACTS_REQUEST_CODE);
}
当用户选择了一个联系人时,它会回到这个方法:
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == CONTACTS_REQUEST_CODE){
if(resultCode == RESULT_OK){
Uri uri = data.getData();
System.out.println("uri: "+uri);
System.out.println("PHONE NUMBER: " + PhoneUtils.getContactPhoneNumber(this, uri.getLastPathSegment()));
}
}
}
哪个调用我的静态util类:
private static final String TAG = "PhoneUtils";
public static String getContactPhoneNumber(Context context, String contactId) {
int type = ContactsContract.CommonDataKinds.Phone.TYPE_MOBILE;
String phoneNumber = null;
String[] whereArgs = new String[] { String.valueOf(contactId), String.valueOf(type) };
Log.d(TAG, "Got contact id: "+contactId);
Cursor cursor = context.getContentResolver().query(
ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
null,
ContactsContract.CommonDataKinds.Phone._ID + " = ? and " + ContactsContract.CommonDataKinds.Phone.TYPE + " = ?",
whereArgs,
null);
int phoneNumberIndex = cursor.getColumnIndexOrThrow(ContactsContract.CommonDataKinds.Phone.NUMBER);
if (cursor != null) {
Log.d(TAG, "Returned contact count: "+cursor.getCount());
try {
if (cursor.moveToFirst()) {
phoneNumber = cursor.getString(phoneNumberIndex);
}
} finally {
cursor.close();
}
}
Log.d(TAG, "Returning phone number: "+phoneNumber);
return phoneNumber;
}
其中contactId = lookupURI.getLastPathSegment();
对于这么简单的事情来说太复杂了! 🙁
附:您可能需要在清单中获得此权限: