Android 通过联系人姓名查询联系人号码


<!-- 读联系人权限 -->
<uses-permission android:name="android.permission.READ_CONTACTS" />
<!-- 写联系人权限 -->
<uses-permission android:name="android.permission.WRITE_CONTACTS" />
<!-- 拨号权限 -->
<uses-permission android:name="android.permission.CALL_PHONE" />


/**
* @param name 联系人姓名
* @描述 查询该联系人下的所有号码
* @作者 tll
* @时间 2016/11/11 17:33
*/
public static List<String> queryNumber(String name, Context context) {
List<String> numbers = new ArrayList<>();
Cursor cursor = null;
Cursor phoneCursor = null;
try {
//使用ContentResolver查找联系人数据
cursor = context.getContentResolver().query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null);
//遍历查询结果,找到所需号码
while (cursor.moveToNext()) {
//获取联系人ID
String contactId = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
//获取联系人的名字
String contactName = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
if (name.equalsIgnoreCase(contactName)) {
// 查看联系人有多少个号码,如果没有号码,返回0
int phoneCount = cursor
.getInt(cursor
.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER));
if (phoneCount > 0) {
// 获得联系人的电话号码列表
phoneCursor = context.getContentResolver().query(
ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
null,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID
+ "=" + contactId, null, null);
if (phoneCursor.moveToFirst()) {
do {
//遍历所有的联系人下面所有的电话号码
String phoneNumber = phoneCursor.getString(phoneCursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
numbers.add(phoneNumber);
} while (phoneCursor.moveToNext());
}
}
//使用ContentResolver查找联系人的电话号码
// Cursor phone = context.getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = " + contactId, null, null);
// if (phone.moveToNext()) {
// String phoneNumber = phone.getString(phone.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
// numbers.add(phoneNumber);
// }
}
}
cursor.close();
} catch (Exception e) {
LogUtil.getLog().e(e.toString());
e.printStackTrace();
} finally {
if (cursor != null) {
cursor.close();
cursor = null;
}
if (phoneCursor != null) {
phoneCursor.close();
phoneCursor = null;
}
}
return numbers;
}


posted on 2016-11-07 11:07  白衣雨果  阅读(1965)  评论(0编辑  收藏  举报