Android 联系人查询
/** * 姓名中含有特殊字符的查找不到 * */ public String getContactID(String name) { String id = "0"; Uri uri = ContactsContract.Contacts.CONTENT_URI; String [] projection = new String[]{ContactsContract.Contacts._ID}; String selection = ContactsContract.Contacts.DISPLAY_NAME_ALTERNATIVE + "='" + name + "'"; Cursor cursor = contentResolver.query(uri, projection, selection, null, null); if(cursor.moveToNext()) { id = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID)); } return id; } /** * 查询的数据为原始数据(姓名含有特殊未经处理) * */ public String getContactId(String contactName) { //读取通讯录的全部的联系人 //需要先在raw_contact表中遍历id,并根据id到data表中获取数据 Uri uri = Uri.parse("content://com.android.contacts/contacts"); Cursor cursor = contentResolver.query(uri, new String[]{ContactsContract.Data._ID}, null, null, null); if (cursor == null) { return null; } while(cursor.moveToNext()) { String id = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));//联系人ID //如果要获得data表中某个id对应的数据 uri = Uri.parse("content://com.android.contacts/contacts/"+id+"/data"); Cursor cursor2 = contentResolver.query(uri, new String[]{"data1"}, "data1='" + contactName + "'",null, null); if (cursor2 == null) { return null; } while(cursor2.moveToNext()){ for (int i = 0; i <cursor2.getColumnCount(); i++) { String type = cursor2.getColumnName(i); try { String val = cursor2.getString(i); if (val != null && val instanceof String && val.equals(contactName)) { // Log.d(TAG, "" + type + ": " + val); return id; } } catch (Exception e) { // e.printStackTrace(); } } } } return null; } /** * 通过关键字搜索联系人,关键字不限于姓名、电话号码 * */ public String searchContactByKeyword(String keyword) { String id = null; Uri uri = Uri.withAppendedPath(ContactsContract.Contacts.CONTENT_FILTER_URI, keyword); // Uri uri2 = Uri.withAppendedPath(ContactsContract.PhoneLookup.CONTENT_FILTER_URI, phoneNumber); 根据电话号码查找联系人 String[] projection = new String[]{ContactsContract.Contacts._ID}; Cursor cursor = contentResolver.query(uri, projection, null, null, null); if (cursor == null) { return null; } if (cursor.moveToFirst()) { id = cursor.getString(cursor.getColumnIndexOrThrow(ContactsContract.Contacts._ID)); } return id; }