Last active
November 19, 2016 13:25
-
-
Save XuQK/6e106af6ea31124e3069fc2ad45f3081 to your computer and use it in GitHub Desktop.
通过联系人名字获取其行动电话号码
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public static String getNumberThroughName(String name) { | |
//获取联系人的 ID 标识 | |
Uri contactUri = ContactsContract.Contacts.CONTENT_URI; | |
String[] queryNameField = new String[] {name}; | |
// 将 Contacts 表里 _ID 这一列,对应 DISPLAY_NAME 为 name 的一行单独提取出来组成数据表 | |
Cursor contactCursor = getActivity().getContentResolver().query(contactUri, | |
new String[] {ContactsContract.Contacts._ID}, | |
ContactsContract.Contacts.DISPLAY_NAME + " = ?", | |
queryNameField, | |
null); | |
String id = null; | |
try { | |
if (contactCursor != null) { | |
contactCursor.moveToFirst(); | |
// 因为数据表中只有一个值,所以 index 直接写成 0 | |
id = contactCursor.getString(0); | |
} | |
} finally { | |
contactCursor.close(); | |
} | |
//根据获取的 ID 获取电话号码 | |
Uri phoneUri = ContactsContract.CommonDataKinds.Phone.CONTENT_URI; | |
String[] queryIdField = new String[] {id}; | |
//将 Phone 表中的 NUMBER 列,CONTACT_ID 值为 ID 的那一行提取出来组成数据表(实际上只包含了 CONTACT_ID 值为 ID 的 NUMBER 这一个数据) | |
Cursor phoneCursor = getActivity().getContentResolver().query(phoneUri, | |
new String[] {ContactsContract.CommonDataKinds.Phone.NUMBER}, | |
ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ?", | |
queryIdField, | |
null); | |
try { | |
if (phoneCursor != null) { | |
phoneCursor.moveToFirst(); | |
// 由于表中只有一个数据,所以 index 直接写成 0,number 就是 monkey 的电话号码了 | |
return phoneCursor.getString(0); | |
} | |
} finally { | |
phoneCursor.close(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment