获取通讯录,电话,姓名,地址邮箱

来源:互联网 发布:天地缓缓知乎 编辑:程序博客网 时间:2024/04/30 18:01
package com.paic.util;import java.util.ArrayList;import java.util.HashMap;import java.util.List;import java.util.Map;import org.json.JSONArray;import org.json.JSONException;import org.json.JSONObject;import android.content.ContentResolver;import android.content.Context;import android.database.Cursor;import android.graphics.Bitmap;import android.net.Uri;import android.provider.ContactsContract;import android.provider.CallLog.Calls;import android.provider.ContactsContract.CommonDataKinds.Email;import android.provider.ContactsContract.CommonDataKinds.Event;import android.provider.ContactsContract.CommonDataKinds.Im;import android.provider.ContactsContract.CommonDataKinds.Nickname;import android.provider.ContactsContract.CommonDataKinds.Note;import android.provider.ContactsContract.CommonDataKinds.Organization;import android.provider.ContactsContract.CommonDataKinds.Phone;import android.provider.ContactsContract.CommonDataKinds.StructuredName;import android.provider.ContactsContract.CommonDataKinds.StructuredPostal;import android.provider.ContactsContract.CommonDataKinds.Website;import android.provider.ContactsContract.Contacts;import android.provider.ContactsContract.Data;import android.util.Log;import com.paic.esale.model.bean.MailsBean;import repack.cz.msebera.android.httpclient.util.TextUtils;/** * Created by ex-huangkeze001 on 2017/9/30. */public class ContactUtil {    public List<Contacts> list;    private Context context;    private JSONArray contactData;    private JSONObject jsonObject;    private List<MailsBean> listNews = new ArrayList<>();    public ContactUtil(Context context) {        this.context = context;    }    // ContactsContract.Contacts.CONTENT_URI= content://com.android.contacts/contacts;    // ContactsContract.Data.CONTENT_URI = content://com.android.contacts/data;    /**     * 获取联系人信息,并把数据转换成json数据     *     * @return [ {},{} ]     * @throws JSONException     */    public String getContactInfo() throws JSONException {        list = new ArrayList<Contacts>();        contactData = new JSONArray();        String mimetype = "";        int oldrid = -1;        int contactId = -1;        // 1.查询通讯录所有联系人信息,通过id排序,我们看下android联系人的表就知道,所有的联系人的数据是由RAW_CONTACT_ID来索引开的        // 所以,先获取所有的人的RAW_CONTACT_ID        Uri uri = ContactsContract.Data.CONTENT_URI; // 联系人Uri;        Cursor cursor = context.getContentResolver().query(uri,                null, null, null, Data.RAW_CONTACT_ID);        int numm = 0;        while (cursor.moveToNext()) {            contactId = cursor.getInt(cursor                    .getColumnIndex(Data.RAW_CONTACT_ID));            if (oldrid != contactId) {                jsonObject = new JSONObject();//                contactData.put("contact" + numm, jsonObject);                contactData.put(jsonObject);                numm++;                oldrid = contactId;            }            mimetype = cursor.getString(cursor.getColumnIndex(Data.MIMETYPE)); // 取得mimetype类型,扩展的数据都在这个类型里面            // 1.1,拿到联系人的各种名字            if (StructuredName.CONTENT_ITEM_TYPE.equals(mimetype)) {                String disName = cursor.getString(cursor                        .getColumnIndex(StructuredName.DISPLAY_NAME));                jsonObject.put("disName", disName);                String prefix = cursor.getString(cursor                        .getColumnIndex(StructuredName.PREFIX));                jsonObject.put("prefix", prefix);                String firstName = cursor.getString(cursor                        .getColumnIndex(StructuredName.FAMILY_NAME));                jsonObject.put("firstName", firstName);                String middleName = cursor.getString(cursor                        .getColumnIndex(StructuredName.MIDDLE_NAME));                jsonObject.put("middleName", middleName);                String lastname = cursor.getString(cursor                        .getColumnIndex(StructuredName.GIVEN_NAME));                jsonObject.put("lastname", lastname);                String suffix = cursor.getString(cursor                        .getColumnIndex(StructuredName.SUFFIX));                jsonObject.put("suffix", suffix);                String phoneticFirstName = cursor.getString(cursor                        .getColumnIndex(StructuredName.PHONETIC_FAMILY_NAME));                jsonObject.put("phoneticFirstName", phoneticFirstName);                String phoneticMiddleName = cursor.getString(cursor                        .getColumnIndex(StructuredName.PHONETIC_MIDDLE_NAME));                jsonObject.put("phoneticMiddleName", phoneticMiddleName);                String phoneticLastName = cursor.getString(cursor                        .getColumnIndex(StructuredName.PHONETIC_GIVEN_NAME));                jsonObject.put("phoneticLastName", phoneticLastName);            }            // 1.2 获取各种电话信息            if (Phone.CONTENT_ITEM_TYPE.equals(mimetype)) {                int phoneType = cursor                        .getInt(cursor.getColumnIndex(Phone.TYPE)); // 手机                if (phoneType == Phone.TYPE_MOBILE) {                    String mobile = cursor.getString(cursor                            .getColumnIndex(Phone.NUMBER));                    jsonObject.put("mobile", mobile);                }                // 住宅电话                if (phoneType == Phone.TYPE_HOME) {                    String homeNum = cursor.getString(cursor                            .getColumnIndex(Phone.NUMBER));                    jsonObject.put("homeNum", homeNum);                }                // 单位电话                if (phoneType == Phone.TYPE_WORK) {                    String jobNum = cursor.getString(cursor                            .getColumnIndex(Phone.NUMBER));                    jsonObject.put("jobNum", jobNum);                }                // 单位传真                if (phoneType == Phone.TYPE_FAX_WORK) {                    String workFax = cursor.getString(cursor                            .getColumnIndex(Phone.NUMBER));                    jsonObject.put("workFax", workFax);                }                // 住宅传真                if (phoneType == Phone.TYPE_FAX_HOME) {                    String homeFax = cursor.getString(cursor                            .getColumnIndex(Phone.NUMBER));                    jsonObject.put("homeFax", homeFax);                } // 寻呼机                if (phoneType == Phone.TYPE_PAGER) {                    String pager = cursor.getString(cursor                            .getColumnIndex(Phone.NUMBER));                    jsonObject.put("pager", pager);                }                // 回拨号码                if (phoneType == Phone.TYPE_CALLBACK) {                    String quickNum = cursor.getString(cursor                            .getColumnIndex(Phone.NUMBER));                    jsonObject.put("quickNum", quickNum);                }                // 公司总机                if (phoneType == Phone.TYPE_COMPANY_MAIN) {                    String jobTel = cursor.getString(cursor                            .getColumnIndex(Phone.NUMBER));                    jsonObject.put("jobTel", jobTel);                }                // 车载电话                if (phoneType == Phone.TYPE_CAR) {                    String carNum = cursor.getString(cursor                            .getColumnIndex(Phone.NUMBER));                    jsonObject.put("carNum", carNum);                } // ISDN                if (phoneType == Phone.TYPE_ISDN) {                    String isdn = cursor.getString(cursor                            .getColumnIndex(Phone.NUMBER));                    jsonObject.put("isdn", isdn);                } // 总机                if (phoneType == Phone.TYPE_MAIN) {                    String tel = cursor.getString(cursor                            .getColumnIndex(Phone.NUMBER));                    jsonObject.put("tel", tel);                }                // 无线装置                if (phoneType == Phone.TYPE_RADIO) {                    String wirelessDev = cursor.getString(cursor                            .getColumnIndex(Phone.NUMBER));                    jsonObject.put("wirelessDev", wirelessDev);                } // 电报                if (phoneType == Phone.TYPE_TELEX) {                    String telegram = cursor.getString(cursor                            .getColumnIndex(Phone.NUMBER));                    jsonObject.put("telegram", telegram);                }                // TTY_TDD                if (phoneType == Phone.TYPE_TTY_TDD) {                    String tty_tdd = cursor.getString(cursor                            .getColumnIndex(Phone.NUMBER));                    jsonObject.put("tty_tdd", tty_tdd);                }                // 单位手机                if (phoneType == Phone.TYPE_WORK_MOBILE) {                    String jobMobile = cursor.getString(cursor                            .getColumnIndex(Phone.NUMBER));                    jsonObject.put("jobMobile", jobMobile);                }                // 单位寻呼机                if (phoneType == Phone.TYPE_WORK_PAGER) {                    String jobPager = cursor.getString(cursor                            .getColumnIndex(Phone.NUMBER));                    jsonObject.put("jobPager", jobPager);                } // 助理                if (phoneType == Phone.TYPE_ASSISTANT) {                    String assistantNum = cursor.getString(cursor                            .getColumnIndex(Phone.NUMBER));                    jsonObject.put("assistantNum", assistantNum);                } // 彩信                if (phoneType == Phone.TYPE_MMS) {                    String mms = cursor.getString(cursor                            .getColumnIndex(Phone.NUMBER));                    jsonObject.put("mms", mms);                }                String mobileEmail = cursor.getString(cursor                        .getColumnIndex(Email.DATA));                jsonObject.put("mobileEmail", mobileEmail);            }        }        // 查找event地址        if (Event.CONTENT_ITEM_TYPE.equals(mimetype)) { // 取出时间类型            int eventType = cursor.getInt(cursor.getColumnIndex(Event.TYPE)); // 生日            if (eventType == Event.TYPE_BIRTHDAY) {                String birthday = cursor.getString(cursor                        .getColumnIndex(Event.START_DATE));                jsonObject.put("birthday", birthday);            }            // 周年纪念日            if (eventType == Event.TYPE_ANNIVERSARY) {                String anniversary = cursor.getString(cursor                        .getColumnIndex(Event.START_DATE));                jsonObject.put("anniversary", anniversary);            }        }        // 获取即时通讯消息        if (Im.CONTENT_ITEM_TYPE.equals(mimetype)) { // 取出即时消息类型            int protocal = cursor.getInt(cursor.getColumnIndex(Im.PROTOCOL));            if (Im.TYPE_CUSTOM == protocal) {                String workMsg = cursor.getString(cursor                        .getColumnIndex(Im.DATA));                jsonObject.put("workMsg", workMsg);            } else if (Im.PROTOCOL_MSN == protocal) {                String workMsg = cursor.getString(cursor                        .getColumnIndex(Im.DATA));                jsonObject.put("workMsg", workMsg);            }            if (Im.PROTOCOL_QQ == protocal) {                String instantsMsg = cursor.getString(cursor                        .getColumnIndex(Im.DATA));                jsonObject.put("instantsMsg", instantsMsg);            }        }        // 获取备注信息        if (Note.CONTENT_ITEM_TYPE.equals(mimetype)) {            String remark = cursor.getString(cursor.getColumnIndex(Note.NOTE));            jsonObject.put("remark", remark);        }        // 获取昵称信息        if (Nickname.CONTENT_ITEM_TYPE.equals(mimetype)) {            String nickName = cursor.getString(cursor                    .getColumnIndex(Nickname.NAME));            jsonObject.put("nickName", nickName);        }        // 获取组织信息        if (Organization.CONTENT_ITEM_TYPE.equals(mimetype)) { // 取出组织类型            int orgType = cursor.getInt(cursor                    .getColumnIndex(Organization.TYPE)); // 单位            if (orgType == Organization.TYPE_CUSTOM) { // if (orgType ==                // Organization.TYPE_WORK)                // {                String company = cursor.getString(cursor                        .getColumnIndex(Organization.COMPANY));                jsonObject.put("company", company);                String jobTitle = cursor.getString(cursor                        .getColumnIndex(Organization.TITLE));                jsonObject.put("jobTitle", jobTitle);                String department = cursor.getString(cursor                        .getColumnIndex(Organization.DEPARTMENT));                jsonObject.put("department", department);            }        }        // 获取网站信息        // 查找通讯地址        if (StructuredPostal.CONTENT_ITEM_TYPE.equals(mimetype)) { // 取出邮件类型            int postalType = cursor.getInt(cursor                    .getColumnIndex(StructuredPostal.TYPE)); // 单位通讯地址            if (postalType == StructuredPostal.TYPE_WORK) {                String street = cursor.getString(cursor                        .getColumnIndex(StructuredPostal.STREET));                jsonObject.put("street", street);                String ciry = cursor.getString(cursor                        .getColumnIndex(StructuredPostal.CITY));                jsonObject.put("ciry", ciry);                String box = cursor.getString(cursor                        .getColumnIndex(StructuredPostal.POBOX));                jsonObject.put("box", box);                String area = cursor.getString(cursor                        .getColumnIndex(StructuredPostal.NEIGHBORHOOD));                jsonObject.put("area", area);                String state = cursor.getString(cursor                        .getColumnIndex(StructuredPostal.REGION));                jsonObject.put("state", state);                String zip = cursor.getString(cursor                        .getColumnIndex(StructuredPostal.POSTCODE));                jsonObject.put("zip", zip);                String country = cursor.getString(cursor                        .getColumnIndex(StructuredPostal.COUNTRY));                jsonObject.put("country", country);            }            // 住宅通讯地址            if (postalType == StructuredPostal.TYPE_HOME) {                String homeStreet = cursor.getString(cursor                        .getColumnIndex(StructuredPostal.STREET));                jsonObject.put("homeStreet", homeStreet);                String homeCity = cursor.getString(cursor                        .getColumnIndex(StructuredPostal.CITY));                jsonObject.put("homeCity", homeCity);                String homeBox = cursor.getString(cursor                        .getColumnIndex(StructuredPostal.POBOX));                jsonObject.put("homeBox", homeBox);                String homeArea = cursor.getString(cursor                        .getColumnIndex(StructuredPostal.NEIGHBORHOOD));                jsonObject.put("homeArea", homeArea);                String homeState = cursor.getString(cursor                        .getColumnIndex(StructuredPostal.REGION));                jsonObject.put("homeState", homeState);                String homeZip = cursor.getString(cursor                        .getColumnIndex(StructuredPostal.POSTCODE));                jsonObject.put("homeZip", homeZip);                String homeCountry = cursor.getString(cursor                        .getColumnIndex(StructuredPostal.COUNTRY));                jsonObject.put("homeCountry", homeCountry);                Log.e("TAG", "住宿 ---------homeStreet=" + homeStreet + "homeCity" + homeCity);            }            // 其他通讯地址            if (postalType == StructuredPostal.TYPE_OTHER) {                String otherStreet = cursor.getString(cursor                        .getColumnIndex(StructuredPostal.STREET));                jsonObject.put("otherStreet", otherStreet);                String otherCity = cursor.getString(cursor                        .getColumnIndex(StructuredPostal.CITY));                jsonObject.put("otherCity", otherCity);                String otherBox = cursor.getString(cursor                        .getColumnIndex(StructuredPostal.POBOX));                jsonObject.put("otherBox", otherBox);                String otherArea = cursor.getString(cursor                        .getColumnIndex(StructuredPostal.NEIGHBORHOOD));                jsonObject.put("otherArea", otherArea);                String otherState = cursor.getString(cursor                        .getColumnIndex(StructuredPostal.REGION));                jsonObject.put("otherState", otherState);                String otherZip = cursor.getString(cursor                        .getColumnIndex(StructuredPostal.POSTCODE));                jsonObject.put("otherZip", otherZip);                String otherCountry = cursor.getString(cursor                        .getColumnIndex(StructuredPostal.COUNTRY));                jsonObject.put("otherCountry", otherCountry);                Log.e("TAG", "住宿 ---------otherStreet=" + otherStreet + "otherStreet" + otherStreet);            }        }        cursor.close();        Log.e("tag", contactData.toString());        return contactData.toString();    }    public List<MailsBean> getdata() {        List<MailsBean> list = new ArrayList<>();        try {            String info = getContactInfo();            JSONArray jsonArray = new JSONArray(info);            for (int i = 0; i < jsonArray.length(); i++) {                JSONObject jsonObject = jsonArray.getJSONObject(i);                MailsBean bean = new MailsBean();                bean.pareToJson(jsonObject);                bean.setmNamePinYin(bean.getNamePinYin());                bean.setmFirstLetter(bean.getFirstLetter());                list.add(bean);            }            Log.e("tag", "list----->" + list.size());        } catch (JSONException e) {            e.printStackTrace();        }        return list;    }    //-------------------方法二------------------------------    /**     * 获取库Phon表字段     **/    private static final String[] PHONES_PROJECTION = new String[]{//            Phone.DISPLAY_NAME, Phone.NUMBER, Contacts.Photo.PHOTO_ID,Phone.CONTACT_ID };            Phone.DISPLAY_NAME, Phone.NUMBER, Phone.CONTACT_ID, StructuredPostal.DATA, Email.DATA};    /**     * 联系人显示名称     **/    private static final int PHONES_DISPLAY_NAME_INDEX = 0;    /**     * 电话号码     **/    private static final int PHONES_NUMBER_INDEX = 1;    /**     * 联系人的ID     **/    private static final int PHONES_PHOTO_ID_INDEX = 2;    /**     * 地址     **/    private static final int PHONES_CONTACT_ID_INDEX = 3;    /**     * 得到手机通讯录联系人信息     **/    private void getPhoneContacts() {        ContentResolver resolver = context.getContentResolver();        // 获取手机联系人        Cursor phoneCursor = resolver.query(Phone.CONTENT_URI, PHONES_PROJECTION, null, null, null);        if (phoneCursor != null) {            while (phoneCursor.moveToNext()) {                //得到手机号码                String phoneNumber = phoneCursor.getString(PHONES_NUMBER_INDEX);//0                //当手机号码为空的或者为空字段 跳过当前循环                if (TextUtils.isEmpty(phoneNumber))                    continue;                //得到联系人名称                String contactName = phoneCursor.getString(PHONES_DISPLAY_NAME_INDEX);//1                //得到联系人ID                Long contactid = phoneCursor.getLong(PHONES_PHOTO_ID_INDEX);//2//                String address = phoneCursor.getString(3);//                String email = phoneCursor.getString(4);                MailsBean bean = new MailsBean();                bean.setLastname(contactName);                bean.setMobile(phoneNumber.replaceAll(" +", ""));//去掉空格//                setEmailAndAddress(resolver,contactid,bean);//                bean.setAddress(address);//                bean.setMobileEmail(email);                bean.setmNamePinYin(bean.getNamePinYin());                bean.setmFirstLetter(bean.getFirstLetter());                listNews.add(bean);            }            phoneCursor.close();        }    }    /**     * 得到手机SIM卡联系人人信息     **/    private void getSIMContacts() {        ContentResolver resolver = context.getContentResolver();        // 获取Sims卡联系人        Uri uri = Uri.parse("content://icc/adn");        Cursor phoneCursor = resolver.query(uri, PHONES_PROJECTION, null, null,                null);        if (phoneCursor != null) {            while (phoneCursor.moveToNext()) {                // 得到手机号码                String phoneNumber = phoneCursor.getString(PHONES_NUMBER_INDEX);                // 当手机号码为空的或者为空字段 跳过当前循环                if (TextUtils.isEmpty(phoneNumber))                    continue;                // 得到联系人名称                String contactName = phoneCursor                        .getString(PHONES_DISPLAY_NAME_INDEX);                String address = phoneCursor.getString(3);                //Sim卡中没有联系人头像                String email = phoneCursor.getString(4);                MailsBean bean = new MailsBean();                bean.setLastname(contactName);                bean.setMobile(phoneNumber.replaceAll(" +", ""));                bean.setMobileEmail(email);                bean.setAddress(address);                bean.setmNamePinYin(bean.getNamePinYin());                bean.setmFirstLetter(bean.getFirstLetter());                listNews.add(bean);            }            phoneCursor.close();        }    }    public List<MailsBean> getListNews() {        listNews.clear();        getPhoneContacts();        getSIMContacts();        for (int i = 0; i < listNews.size(); i++) {            for (int k = 0; k < listNews.size(); k++) {                //如果 姓名和电话一致 删除一个  除重                if (i != k && listNews.get(i).getLastname().equals(listNews.get(k).getLastname()) && listNews.get(i).getMobile().equals(listNews.get(k).getMobile())) {                    listNews.remove(k);                    k--;                }            }        }        return listNews;    }    //-------    public List<MailsBean>  getAllContact() {        //获取联系人信息的Uri        Uri uri = ContactsContract.Contacts.CONTENT_URI;        //获取ContentResolver        ContentResolver contentResolver = context.getContentResolver();        //查询数据,返回Cursor        Cursor cursor = contentResolver.query(uri, null, null, null, null);        List<MailsBean> lsBean=new ArrayList<>();        while(cursor.moveToNext())        {            MailsBean bean=new MailsBean();            //获取联系人的ID            String contactId = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));            //获取联系人的姓名            String name = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));            //构造联系人信息            bean.setLastname(name);            String id = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));//联系人ID            //查询电话类型的数据操作            Cursor phones = contentResolver.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,                    null,                    ContactsContract.CommonDataKinds.Phone.CONTACT_ID +" = "+ contactId,                    null, null);            while(phones.moveToNext())            {                String phoneNumber = phones.getString(phones.getColumnIndex(                        ContactsContract.CommonDataKinds.Phone.NUMBER));                //添加Phone的信息                bean.setMobile(phoneNumber.replaceAll(" +", ""));            }            phones.close();            String[] proj={Email.DATA};            //查询Email类型的数据操作            Cursor emails = contentResolver.query(ContactsContract.CommonDataKinds.Email.CONTENT_URI,                    null,                    ContactsContract.CommonDataKinds.Email.CONTACT_ID + " = " + contactId,                    null, null);            while (emails.moveToNext())            {            Log.e("TAG","---ema=---"+emails.getString(0));                String emailAddress = emails.getString(emails.getColumnIndex(                        ContactsContract.CommonDataKinds.Email.DATA));                //添加Email的信息                bean.setMobileEmail(emailAddress);                Log.e("TAG","------email="+emailAddress);            }            emails.close();            //Log.i("=========ddddddddddd=====", sb.toString());            //查询==地址==类型的数据操作.StructuredPostal.TYPE_WORK            Cursor address = contentResolver.query(ContactsContract.CommonDataKinds.StructuredPostal.CONTENT_URI,                    null,                    ContactsContract.CommonDataKinds.StructuredPostal.CONTACT_ID + " = " + contactId,                    null, null);            while (address.moveToNext())            {                String workAddress = address.getString(address.getColumnIndex(                        ContactsContract.CommonDataKinds.StructuredPostal.DATA));                Log.e("TAG","------workAddress="+workAddress);                //添加Email的信息                bean.setAddress(workAddress);            }            address.close();            bean.setmNamePinYin(bean.getNamePinYin());            bean.setmFirstLetter(bean.getFirstLetter());            lsBean.add(bean);        }//        Log.e("=========list=====", list.toString());//        cursor.close();        for (int i = 0; i < lsBean.size(); i++) {            for (int k = 0; k < lsBean.size(); k++) {                //如果 姓名和电话一致 删除一个  除重                if (i != k && lsBean.get(i).getLastname().equals(lsBean.get(k).getLastname()) && lsBean.get(i).getMobile().equals(lsBean.get(k).getMobile())) {                    lsBean.remove(k);                    k--;                }            }        }        return lsBean;    }    private void setEmailAndAddress(ContentResolver resolver,Long contactid,MailsBean bean){        //查询Email类型的数据操作        Cursor emails = resolver.query(ContactsContract.CommonDataKinds.Email.CONTENT_URI,                null,                ContactsContract.CommonDataKinds.Email.CONTACT_ID + " = " + contactid,                null, null);        while (emails.moveToNext())        {            String emailAddress = emails.getString(emails.getColumnIndex(                    ContactsContract.CommonDataKinds.Email.DATA));            //添加Email的信息            bean.setMobileEmail(emailAddress);            Log.e("TAG","------email="+emailAddress);        }        emails.close();        //Log.i("=========ddddddddddd=====", sb.toString());        //查询==地址==类型的数据操作.StructuredPostal.TYPE_WORK        Cursor address = resolver.query(ContactsContract.CommonDataKinds.StructuredPostal.CONTENT_URI,                null,                ContactsContract.CommonDataKinds.StructuredPostal.CONTACT_ID + " = " + contactid,                null, null);        while (address.moveToNext())        {            String workAddress = address.getString(address.getColumnIndex(                    ContactsContract.CommonDataKinds.StructuredPostal.DATA));            Log.e("TAG","------workAddress="+workAddress);            //添加Email的信息            bean.setAddress(workAddress);        }        address.close();    }}
阅读全文
0 0
原创粉丝点击