做项目想要获取手机联系人相关信息,查了网上的很多方法,发现在一些手机上并不匹配,找到的联系人信息 并不完善,经过研究,最终找到一个比较不错的,大家可以参考修改,ContactBean是封装联系人的实体类,为了在android手机自己的应用上显示ContactLogi是联系人逻辑类,用于获取手机联系人信息,下面直接上代码吧:
/**
* 联系人实体类
* @author Administrator
*/
public class ContactBean implements Serializable{
/**
*
*/
private static final long serialVersionUID = -5079595803545960943L;
private int id;
private String name;
private String phoneNum;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPhoneNum() {
return phoneNum;
}
public void setPhoneNum(String phoneNum) {
this.phoneNum = phoneNum;
}
}
/**
*获取联系人的方法类
*/
public class ContactLogic {
// These are the Contacts rows that we will retrieve.
static final String[] CONTACTS_SUMMARY_PROJECTION = new String[] {
ContactsContract.Contacts._ID,
ContactsContract.Contacts.DISPLAY_NAME,
ContactsContract.Contacts.PHOTO_ID,
};
/**
* 获取手机系统联系人信息的静态方法-->亲测有效
* @return
*/
public static List<ContactBean> getPhoneContacts(Context ctx) {
List<ContactBean> contacts = new ArrayList<ContactBean>();
String select = "((" + ContactsContract.Contacts.DISPLAY_NAME + " NOTNULL) AND ("
+ ContactsContract.Contacts.HAS_PHONE_NUMBER + "=1) AND ("
+ ContactsContract.Contacts.DISPLAY_NAME + " != '' ))";
try {
Cursor cursor = ctx.getContentResolver().query(ContactsContract.Contacts.CONTENT_URI,
CONTACTS_SUMMARY_PROJECTION,
select,
null, ContactsContract.Contacts.DISPLAY_NAME + " COLLATE LOCALIZED ASC");
while (cursor.moveToNext()) {
int indexId = cursor.getColumnIndex(ContactsContract.Contacts._ID);
String contactId = cursor.getString(indexId);
int indexDisplayName = cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME);
String name = cursor.getString(indexDisplayName);
Cursor phones = ctx.getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = " + contactId, null, null);
ContactBean data = new ContactBean();
data.setId(Integer.valueOf(contactId));
data.setName(name);
//一个人电话可能不止一个,所以可能是一个集合,因此在设置实体类的时候,手机号那里可以设置成一个集合,集合中放置Phone的实体类
while (phones.moveToNext()) {
String phoneNumber = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
data.setPhoneNum(phoneNumber);
}
contacts.add(data);
phones.close();
}
cursor.close();
if(contacts != null) {
//排序
}
} catch (Exception e) {
e.printStackTrace();
}
return contacts;
}
}