在manifest添加以下权限
<uses-permission android:name="android.permission.READ_CONTACTS" />
/**
* 获取通讯录列表
* @param s 查询条件,null时为查询所有联系人。
* s = "刘"则查询所有包含刘字的联系人
*/
private void getCallList(final String s) {
//新开线程,防止通讯录太多联系人,卡顿
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
String[] cols = {ContactsContract.PhoneLookup.DISPLAY_NAME,
ContactsContract.CommonDataKinds.Phone.NUMBER,
ContactsContract.CommonDataKinds.Phone.PHOTO_ID,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID};
Cursor cursor;
if (s!=null){
//设置查询条件
String selection = ContactsContract.PhoneLookup.DISPLAY_NAME + " like '%" + s
+ "%' or " + ContactsContract.CommonDataKinds.Phone.NUMBER + " like '%" + s + "%'";
//ContactsContract.CommonDataKinds.Phone.SORT_KEY_PRIMARY 这个参数是让查询结果按字母排序
cursor = getContext().getContentResolver()
.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
cols, selection, null, ContactsContract.CommonDataKinds.Phone.SORT_KEY_PRIMARY);
}else {
cursor = getContext().getContentResolver()
.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
cols, null, null, ContactsContract.CommonDataKinds.Phone.SORT_KEY_PRIMARY);
}
int nameFieldColumnIndex = cursor.getColumnIndex(ContactsContract.PhoneLookup.DISPLAY_NAME);
int contactIdFieldColumnIndex = cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.CONTACT_ID);
int numberFieldColumnIndex = cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER);
int photoFieldColumnIndex = cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.PHOTO_ID);
for (int i = 0; i < cursor.getCount(); i++) {
cursor.moveToPosition(i);
String name = cursor.getString(nameFieldColumnIndex);//联系人名称
Long contactId = cursor.getLong(contactIdFieldColumnIndex);//联系人ID
Long photoId = cursor.getLong(photoFieldColumnIndex);//联系人头像ID
String phoneNum = cursor.getString(numberFieldColumnIndex);//联系人手机号
Log.i("Msg","name:"+name);
Log.i("Msg","contactId:"+contactId);
Log.i("Msg","photoId:"+photoId);
Log.i("Msg","phoneNum:"+phoneNum);
//在此处执行相应的存储操作,之后会查询下一条联系人信息
}
cursor.close();
//此处执行查询完毕要执行的操作,若要更新UI,要使用handle
}
});
thread.start();
可以通过头像id和联系人id获取联系人的头像
private Bitmap getBitmap(Long photoId, Long contactId) {
Bitmap contactPhoto;//photoid 大于0 表示联系人有头像 如果没有给此人设置头像则给他一个默认的
if(photoId > 0 ) {
Uri uri = ContentUris.withAppendedId(ContactsContract.Contacts.CONTENT_URI,contactId);
InputStream input = ContactsContract.Contacts.openContactPhotoInputStream(getContentResolver(), uri);
contactPhoto = BitmapFactory.decodeStream(input);
}else {
contactPhoto = BitmapFactory.decodeResource(getResources(), R.drawable.icon_shareapp);
}
return contactPhoto;
}