1、前言
最近在做公司项目的时候遇到一个添加手机联系人的需求,主要有以下几个功能点:
- 读取联系人:读取用户手机上的通讯录里的联系人列表
- 好友排序:按照拼音顺序对好友进行排序,兼容英文数字符号等
- 字母索引:右侧字母导航条,既可拖动也可点击,联动ListView滑动
- 匹配:最后要将通讯录里的联系人列表与后台数据库里的用户表进行匹配
最终的大致效果如下:
特意写篇博客将整个实现过程记录下来,方便以后再次遇到这样的需求的时候可以直接使用CV大法,也希望能帮到刚好有这方面需求的朋友。
2、读取联系人
读取手机通讯录里的联系人主要是通过ContentResolver 来获取的,代码比较固定,直接贴代码:
先定义一个用来接收联系人的数据bean,主要是对id,name和phone三个字段进行赋值,其他字段主要是为了排序和匹配用户表用到的。
/**
* @author hydCoder
* @date 2017/10/11 10:50
* @desc 手机联系人的数据bean
* @email hyd_coder@163.com
*/
public class ContactInfo implements Comparable<ContactInfo> {
public String id;
public String name;
public String phone;
public String pinyin; // 姓名对应的拼音
public String firstLetter; // 拼音的首字母
public String userAvatar;
public String userName;
public String userNick;
public int isFriend;
public String userId;
public int gradeLevel;
public String userPosition;
public String userCompany;
public int userType;
public boolean isUser = false;
public ContactInfo(String id, String name, String phone) {
this.id = id;
this.name = name;
this.phone = phone;
pinyin = Cn2Spell.getPinYin(name); // 根据姓名获取拼音
firstLetter = pinyin.substring(0, 1).toUpperCase(); // 获取拼音首字母并转成大写
if (!firstLetter.matches("[A-Z]")) { // 如果不在A-Z中则默认为“#”
firstLetter = "#";
}
}
@Override
public int compareTo(@NonNull ContactInfo another) {
if (firstLetter.equals("#") && !another.firstLetter.equals("#")) {
return 1;
} else if (!firstLetter.equals("#") && another.firstLetter.equals("#")){
return -1;
} else {
return pinyin.compareToIgnoreCase(another.pinyin);
}
}
}
获取联系人数据的工具类:
/**
* @author hydCoder
* @date 2017/10/11 10:53
* @desc 获取手机联系人数据
* @email hyd_coder@163.com
*/
public class ContactUtils {
/**
* 获取联系人数据
*
* @param context
* @return
*/
public static List<ContactInfo> getAllContacts(Context context) {
List<ContactInfo> list = new ArrayList<>();
// 获取解析者
ContentResolver resolver = context.getContentResolver();
// 访问地址
Uri raw_contacts = Uri.parse("content://com.android.contacts/raw_contacts");
Uri data = Uri.parse("content://com.android.contacts/data");
// 查询语句
// select contact_id from raw_contacts;//1 2 3 4
// select mimetype,data1 from view_data where raw_contact_id=3;
// Cursor cursor=resolver.query(访问地址, 返回字段 null代表全部, where 语句, 参数, 排序)
Cursor cursor = resolver.query(raw_contacts, new String[] { "contact_id" }, null, null, null);
while (cursor.moveToNext()) {
// getColumnIndex根据名称查列号
String id = cursor.getString(cursor.getColumnIndex("contact_id"));
// 创建实例
String name = "";
String phone = "";
Cursor item = resolver.query(data, new String[] { "mimetype", "data1" }, "raw_contact_id=?", new String[] { id }, null);
while (item.moveToNext()) {
String mimetype = item.getString(item.getColumnIndex("mimetype"));
String data1 = item.getString(item.getColumnIndex("data1"));
if ("vnd.android.curso