在写安卓程序的时候,需要获取联系人的信息,需求是根据联系人姓名拼音的首字母查询联系人的信息,也就是说给定一个字母,要查出所有的拼音以该字母开头的联系人。在网上看了好多博客,都建议说使用SORT_KEY_PRIMARY字段,看了下Android源码,该字段返回的的确是拼音拼写,然而我用的时候,它返回的还是联系人的名称,没有拼音!可以使用它排序联系人,但无法实现检索功能!说明一下,我用的是Android6.0系统。我百思不得其解,为什么呢?再看了一下那些博客的时间,都是14年或者更早的。然后我又搜了一下Android6.0版本的联系人查询方法,终于在一篇博客中找到了答案,使用“phonebook_label”字段,它可以返回联系人名称的首字母,使用它就可以完成我们的功能了。附代码片段:
private static final String PHONE_BOOK_LABEL = "phonebook_label";
private void query(String firstLetter){
try {
Uri uri = ContactsContract.CommonDataKinds.Phone.CONTENT_URI;
String[] projection = new String[] { ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME,
ContactsContract.CommonDataKinds.Phone.NUMBER,
PHONE_BOOK_LABEL
};
String selection = PHONE_BOOK_LABEL + " = '" + firstLetter + "' and " + ContactsContract.CommonDataKinds.Phone.HAS_PHONE_NUMBER + " = '1'";
Cursor cursor = getContentResolver().query(
uri, projection, selection, null, ContactsContract.CommonDataKinds.Phone.SORT_KEY_PRIMARY);
while(cursor.moveToNext()) {
String contactPhone = cursor
.getString(cursor
.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
String name = cursor.getString(0);
contactPhone = contactPhone.replace(" ", "");
if(contactPhone.length() >= 11){
contactPhone = contactPhone.substring(contactPhone.length() - 11, contactPhone.length());
if(Pattern.matches("^1[0-9]{10}$", contactPhone)){
System.out.println("{name : " + name + "; mobile : " + contactPhone + "}");
}
}
}
if(cursor != null){
cursor.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
参考博客链接: http://blog.csdn.net/chenkai19920410/article/details/50167307