工作笔记:近期工作中有个需求是需要获取手机中联系人的信息,所以将它记录下来,便于以后可以借鉴;
代码:
public static List<ContactInfo> getContactList(Context context){
//获得ContentResolver对象,用于开provider的锁
ContentResolver resolver=context.getContentResolver();
//以content://开头
Uri uri=Uri.parse("content://com.android.contacts/raw_contacts"); //路径全部小写,csdn编辑器原因有时候会显示错误的大写
Cursor cursor=resolver.query(uri, new String[]{"_id"}, null, null, null);
List<ContactInfo> infos=new ArrayList<ContactInfo>();
while(cursor.moveToNext()){
String _id=cursor.getString(0);
Uri dataUri=Uri.parse("content://com.android.contacts/data");
Cursor dataCursor=resolver.query(dataUri, new String[]{"mimetype","data1"}, "raw_contact_id=?",new String[]{_id} , null);
ContactInfo info=new ContactInfo();
while(dataCursor.moveToNext()){
String mimetype=dataCursor.getString(0);
if(mimetype.equals("vnd.android.cursor.item/phone_v2")){
String phone=dataCursor.getString(1);
info.setPhone(phone);
}
if(mimetype.equals("vnd.android.cursor.item/name")){
String name=dataCursor.getString(1);
info.setName(name);
}
}
dataCursor.close();
infos.add(info);
}
cursor.close();
return infos;
}
ContacInfo的代码如下:
public class ContactInfo {
private String name;
private String phone;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public ContactInfo(String name, String phone) {
super();
this.name = name;
this.phone = phone;
}
public ContactInfo() {
super();
// TODO Auto-generated constructor stub
}
@Override
public String toString() {
return "ContactInfo [name=" + name + ", phone=" + phone + "]";
}
}