Android 获得联系人并排序

方式一:通过观察导出的联系人数据库的相关字段,根据字段去查询(在有些手机上会查询不全,并且该类没有实现排序)

import android.content.Context;
import android.database.Cursor;
import android.net.Uri;

import com.wjustudio.phoneManager.Common.AppConstants;
import com.wjustudio.phoneManager.javaBean.Contact;

import java.util.ArrayList;

/**
 * 作者:songwenju on 2016/4/2 22:00
 * 邮箱:songwenju01@163.com
 */
public class ContactUtil {

    /**
     * 获得系统联系人
     *
     * @param context
     * @return
     */
    public static ArrayList<Contact> getContact(Context context) {
        ArrayList<Contact> contacts = new ArrayList<>();
        Contact contact;
        String[] projection = {"data1", "mimetype"};
        Cursor rawCursor = context.getContentResolver().query(Uri.parse(AppConstants.RAW_CONTACTS),
                new String[]{"contact_id"}, null, null, null);
        if (rawCursor != null && rawCursor.getCount() > 0) {
            LogUtil.i("ContactUtil", "the number of contact:" + rawCursor.getCount());
            while (rawCursor.moveToNext()) {
                String contact_id = rawCursor.getString(rawCursor.getColumnIndex("contact_id"));
                LogUtil.i("contactUtil","contact_id:"+contact_id);
                if (contact_id != null) {
                    Cursor dataCursor = context.getContentResolver().query(
                            Uri.parse(AppConstants.DATA_CONTACTS), projection,
                            "raw_contact_id = ?", new String[]{contact_id}, null);
                    if (dataCursor != null && dataCursor.getCount() > 0) {
                        contact = new Contact();
                        while (dataCursor.moveToNext()) {
                            String data1 = dataCursor.getString(dataCursor.getColumnIndex("data1"));
                            data1 = data1.trim().replaceAll("-","").replaceAll(" ","");
                            String mimetype = dataCursor.getString(dataCursor.getColumnIndex("mimetype"));
                            switch (mimetype) {
                                case "vnd.android.cursor.item/name":
                                    contact.contact_name = data1;
                                    if (ChineseUtil.isChinese(data1.charAt(0))){
                                        contact.pinYin = PinYinUtil.toPinyin(data1);
                                    }else {
                                        contact.pinYin = data1;
                                    }
                                    break;
                                case "vnd.android.cursor.item/email_v2":
                                    contact.email = data1;
                                    break;
                                case "vnd.android.cursor.item/phone_v2":
                                    contact.contact_phoneNum = data1;
                                    break;
                            }
                        }
                        contacts.add(contact);
                    }
                }
            }
        }
        LogUtil.e("contactUtil","contactNum:"+contacts.size());
        return contacts;
    }

}

对应的bean

package com.wjustudio.contactdemo;

import java.util.ArrayList;
import java.util.List;

/**
 * 作者:songwenju on 2016/4/2 22:01
 * 邮箱:songwenju01@163.com
 */
public class Contact {
    public String name;
    public String pinYin;
    public List<String> telephoneNumber = new ArrayList<>();
    public String email;

    @Override
    public String toString() {
        return "Contact{" +
                "name='" + name + '\'' +
                ", pinYin='" + pinYin + '\'' +
                ", telephoneNumber=" + telephoneNumber +
                ", email='" + email + '\'' +
                '}';
    }
}

对应的AppConstants中两个字段

/**
 * App所用的常量
 * 作者:songwenju on 2016/1/31 11:39
 * 邮箱:songwenju01@163.com
 */
public class AppConstants {
    public static final String RAW_CONTACTS = "content://com.android.contacts/raw_contacts";
    public static final String DATA_CONTACTS = "content://com.android.contacts/data";
}

方式二:通过系统提供的字段来获取数据,并实现了按拼音排序

import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.provider.ContactsContract;
import android.text.TextUtils;

import com.wjustudio.phoneManager.javaBean.Contact;

import net.sourceforge.pinyin4j.PinyinHelper;
import net.sourceforge.pinyin4j.format.HanyuPinyinCaseType;
import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat;
import net.sourceforge.pinyin4j.format.HanyuPinyinToneType;
import net.sourceforge.pinyin4j.format.HanyuPinyinVCharType;

import java.util.ArrayList;

public class ContactUtils {

    public static ArrayList<Contact> getContact(Context context) {
        ArrayList<Contact> listMembers = new ArrayList<>();
        Cursor cursor = null;
        try {
            Uri uri = ContactsContract.CommonDataKinds.Phone.CONTENT_URI;
            // 这里是获取联系人表的电话里的信息  包括:名字,联系人id,电话号码;
            // 然后在根据"sort-key"排序
            cursor = context.getContentResolver().query(
                    uri,
                    new String[] { "display_name", "contact_id", "data1" },
                    null, null, "sort_key");

            if (cursor != null && cursor.moveToFirst()) {
                LogUtil.e("contactUtil", "ContactCount:" + cursor.getCount());
                while (cursor.moveToNext()){
                    Contact contact = new Contact();
                    String contact_phoneNum = cursor.getString(cursor
                            .getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
                    String name = cursor.getString(cursor.getColumnIndex(
                            ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
                    int contact_id = cursor.getInt(cursor
                            .getColumnIndex(ContactsContract.CommonDataKinds.Phone.CONTACT_ID));
                    contact.contact_name = name;
                    contact.contact_phoneNum = contact_phoneNum.replaceAll("[^0-9]", "");
                    contact.contact_id = contact_id;
                    contact.pinYin = getPingYin(name);
                    LogUtil.e("contactUtils", "contact:" + contact.toString());
                    if (name != null)
                        listMembers.add(contact);
                }

            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (cursor != null){
                cursor.close();
            }
        }
        return listMembers;
    }


    /**
     * 将字符串中的中文转化为拼音,其他字符不变
     *
     * @param inputString 输入的中文汉字
     * @return 获得的拼音
     */
    public static String getPingYin(String inputString) {
        if (TextUtils.isEmpty(inputString)) {
            return "";
        }
        HanyuPinyinOutputFormat format = new HanyuPinyinOutputFormat();
        format.setCaseType(HanyuPinyinCaseType.LOWERCASE);
        format.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
        format.setVCharType(HanyuPinyinVCharType.WITH_V);

        char[] input = inputString.trim().toCharArray();
        String output = "";

        try {
            for (char anInput : input) {
                if (Character.toString(anInput).matches(
                        "[\\u4E00-\\u9FA5]+")) {
                    String[] temp = PinyinHelper.toHanyuPinyinStringArray(
                            anInput, format);
                    if (temp == null || TextUtils.isEmpty(temp[0])) {
                        continue;
                    }
                    output += temp[0].replaceFirst(temp[0].substring(0, 1),
                            temp[0].substring(0, 1).toUpperCase());
                } else
                    output += Character.toString(anInput);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return output;
    }


}


对应的bean

/**
 * author:songwenju on 16-4-7 11 : 07
 * Email: songwenju01@163.com
 */
public class Contact {
    public String contact_name;
    public String contact_phoneNum;
    public int contact_id;
    public String email;
    //public List<String> telephoneNumber = new ArrayList<>();
    public String pinYin;
    @Override
    public String toString() {
        return "Contact{" +
                "contact_name='" + contact_name + '\'' +
                ", contact_phoneNum='" + contact_phoneNum + '\'' +
                ", contact_id=" + contact_id +
                ", email='" + email + '\'' +
                ", pinYin='" + pinYin + '\'' +
                '}';
    }

}

联系人数据库里面联系人和电话号码是分别存在两个表里面的,因为存在一个联系人拥有几个号码的情况,所以android为联系人和手机号码分别单独创建了相应的视图。

联系人信息的视图里面只保存与联系人相关的资料,例如姓名,是否有手机号码等。

而手机号码资料则是每一个电话号码为一条记录,如果有一个联系人有3个号码,则里面会出现3个该联系人的记录,号码分别为他的三个号码。

如果是需要读取联系人信息,传入的URI为:ContactsContract.Contacts.CONTENT_URI

如果是需要读取手机号码信息传入的URI为:ContactsContract.CommonDataKinds.Phone.CONTENT_URI

下篇文章将写一个完整的小项目去实现读联系人,并且以自定义View的形式展示出来。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值