代码:
private String getContactNameByPhoneNumber(String number) {
if (TextUtils.isEmpty(number)) {
return null;
}
final ContentResolver resolver = getContentResolver();
Uri lookupUri = null;
String[] projection = new String[] { PhoneLookup._ID, PhoneLookup.DISPLAY_NAME };
Cursor cursor = null;
try {
lookupUri = Uri.withAppendedPath(PhoneLookup.CONTENT_FILTER_URI, Uri.encode(number));
cursor =resolver.query(lookupUri, projection, null, null, null);
} catch (Exception ex) {
ex.printStackTrace();
try {
lookupUri = Uri.withAppendedPath(android.provider.Contacts.Phones.CONTENT_FILTER_URL,
Uri.encode(number));
cursor = resolver.query(lookupUri, projection, null, null, null);
} catch (Exception e) {
e.printStackTrace();
}
}
String name = null;
if (cursor != null && cursor.getCount() > 0 && cursor.moveToFirst()) {
name = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
}
cursor.close();
return name;
}