Android按照拼音排序獲取聯絡人並根據拼音首字母獲取聯絡人
阿新 • • 發佈:2019-01-02
在寫安卓程式的時候,需要獲取聯絡人的資訊,需求是根據聯絡人姓名拼音的首字母查詢聯絡人的資訊,也就是說給定一個字母,要查出所有的拼音以該字母開頭的聯絡人。在網上看了好多部落格,都建議說使用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