Android 联系人管理(包括大部分字段),增删该查,批量插入、删除、更新,等等; 可能有问题,还望指证。

来源:互联网 发布:知乎120条神回复集锦 编辑:程序博客网 时间:2024/05/18 17:57
  
  1. package com.szwistar.emistar.phone;  
  2.   
  3. import java.util.ArrayList;  
  4. import java.util.HashMap;  
  5. import java.util.HashSet;  
  6. import java.util.List;  
  7. import java.util.Map;  
  8. import java.util.Set;  
  9.   
  10. import android.content.ContentProviderOperation;  
  11. import android.content.ContentProviderOperation.Builder;  
  12. import android.content.ContentProviderResult;  
  13. import android.content.ContentResolver;  
  14. import android.content.ContentUris;  
  15. import android.content.ContentValues;  
  16. import android.database.Cursor;  
  17. import android.net.Uri;  
  18. import android.provider.ContactsContract;  
  19. import android.provider.ContactsContract.CommonDataKinds.Email;  
  20. import android.provider.ContactsContract.CommonDataKinds.Event;  
  21. import android.provider.ContactsContract.CommonDataKinds.GroupMembership;  
  22. import android.provider.ContactsContract.CommonDataKinds.Im;  
  23. import android.provider.ContactsContract.CommonDataKinds.Nickname;  
  24. import android.provider.ContactsContract.CommonDataKinds.Note;  
  25. import android.provider.ContactsContract.CommonDataKinds.Organization;  
  26. import android.provider.ContactsContract.CommonDataKinds.Phone;  
  27. import android.provider.ContactsContract.CommonDataKinds.StructuredName;  
  28. import android.provider.ContactsContract.CommonDataKinds.StructuredPostal;  
  29. import android.provider.ContactsContract.CommonDataKinds.Website;  
  30. import android.provider.ContactsContract.Contacts;  
  31. import android.provider.ContactsContract.Data;  
  32. import android.provider.ContactsContract.Groups;  
  33. import android.provider.ContactsContract.RawContacts;  
  34. import android.util.Log;  
  35.   
  36. import com.szwistar.emistar.Const;  
  37. import com.szwistar.emistar.util.Utils;  
  38.   
  39. /** 
  40.  * 提供管理通讯录provide 
  41.  * @author fukun 
  42.  * 
  43.  */  
  44. public class ContactsResolver {  
  45.       
  46.     private ContentResolver resolver;  
  47.       
  48.     public ContactsResolver(ContentResolver resolver) {  
  49.         this.resolver = resolver;  
  50.     }  
  51.       
  52.     /** 
  53.      * 批量插入联系人 
  54.      * @param contacts 
  55.      * @return 
  56.      */  
  57.     @SuppressWarnings("unchecked")  
  58.     public HashMap<String, Object> insertContacts(List<Map<String, Object>> contacts) {  
  59.         HashMap<String, Object> addResult = new HashMap<String, Object>();  
  60.         if (Utils.isEmpty(contacts)) {  
  61.             addResult.put("result""0");  
  62.             addResult.put("obj""无效插入,联系人信息不完整!");  
  63.             return addResult;  
  64.         }  
  65.         //批量插入的内容集合  
  66.         ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>();  
  67.         ContentProviderOperation op = null;  
  68.         int rawIndex = 0;  
  69.         Builder builder = null;  
  70.           
  71.         for (Map<String, Object> contact : contacts) {  
  72.             rawIndex = ops.size();  
  73.               
  74.             String displayName          = (String) contact.get("displayName");  
  75.             String familyName           = (String) contact.get("familyName");  
  76.             String middleName           = (String) contact.get("middleName");  
  77.             String givenName            = (String) contact.get("givenName");  
  78.             String prefix               = (String) contact.get("prefix");  
  79.             String suffix               = (String) contact.get("suffix");  
  80.             String phoneticName         = (String) contact.get("phoneticName");  
  81.             String phoneticFamilyName   = (String) contact.get("phoneticFamilyName");  
  82.             String phoneticMiddleName   = (String) contact.get("phoneticMiddleName");  
  83.             String phoneticGivenName    = (String) contact.get("phoneticGivenName");  
  84.             String nickName             = (String) contact.get("nickName");  
  85.             String birthday             = (String) contact.get("birthday");  
  86.             String anniversary          = (String) contact.get("anniversary");  
  87.             String note                 = (String) contact.get("note");  
  88.             String company              = (String) contact.get("company");  
  89.             String job                  = (String) contact.get("job");  
  90.             String department           = (String) contact.get("department");  
  91.               
  92.             Map<String, Object> phones    = (Map<String, Object>) contact.get("phones");  
  93.             Map<String, Object> emails    = (Map<String, Object>) contact.get("emails");  
  94.             Map<String, Object> address = (Map<String, Object>) contact.get("addresses");  
  95.             Map<String, Object> ims   = (Map<String, Object>) contact.get("ims");  
  96.             Map<String, Object> urls  = (Map<String, Object>) contact.get("urls");  
  97.             Map<String, Object> groups    = (Map<String, Object>) contact.get("groups");  
  98.               
  99.             //如果都为空,循环下一个,联系人信息  
  100.             if (Utils.isEmpty(displayName) && Utils.isEmpty(familyName)   
  101.                     && Utils.isEmpty(middleName) && Utils.isEmpty(givenName)  
  102.                     && Utils.isEmpty(prefix) && Utils.isEmpty(suffix)  
  103.                     && Utils.isEmpty(phoneticFamilyName) && Utils.isEmpty(phoneticName)  
  104.                     && Utils.isEmpty(phoneticGivenName) && Utils.isEmpty(phoneticMiddleName)  
  105.                     && Utils.isEmpty(nickName) && Utils.isEmpty(birthday)  
  106.                     && Utils.isEmpty(anniversary) && Utils.isEmpty(note)  
  107.                     && Utils.isEmpty(company) && Utils.isEmpty(job) && Utils.isEmpty(department)  
  108.                     && Utils.isEmpty(phones) && Utils.isEmpty(emails)  
  109.                     && Utils.isEmpty(address) && Utils.isEmpty(ims)  
  110.                     && Utils.isEmpty(urls)) {  
  111.                 continue;  
  112.             }  
  113.             //数据表 uri  
  114.             Uri uri = Data.CONTENT_URI;  
  115.               
  116.             //Uri uri = RawContacts.CONTENT_URI; content://com.android.contacts/raw_contacts  
  117.             //此处.withValue("account_name", null)一定要加,不然会抛NullPointerException  
  118.             //withYieldAllowed(true)//为了避免这种死锁的数据库  
  119.             op = ContentProviderOperation.newInsert(RawContacts.CONTENT_URI)  
  120.                         .withValue(RawContacts.ACCOUNT_TYPE, null)  
  121.                         .withValue(RawContacts.ACCOUNT_NAME, null)  
  122.                         .withYieldAllowed(true)  
  123.                         .build();  
  124.             ops.add(op);  
  125.             //插入姓名  
  126.             if (!Utils.isEmpty(displayName) || !Utils.isEmpty(familyName) || !Utils.isEmpty(middleName)  
  127.                     || !Utils.isEmpty(givenName) || !Utils.isEmpty(prefix) || !Utils.isEmpty(suffix)   
  128.                     || !Utils.isEmpty(phoneticName) || !Utils.isEmpty(phoneticFamilyName)   
  129.                     || !Utils.isEmpty(phoneticMiddleName) || !Utils.isEmpty(phoneticGivenName)) {  
  130.                 Builder tempBuilder = ContentProviderOperation.newInsert(uri)  
  131.                         .withValueBackReference(Data.RAW_CONTACT_ID, rawIndex)  
  132.                         .withValue(Data.MIMETYPE, StructuredName.CONTENT_ITEM_TYPE)  
  133.                         .withYieldAllowed(true);  
  134.                 //插入显示名称  
  135.                 if (!Utils.isEmpty(displayName)) {  
  136.                     tempBuilder.withValue(StructuredName.DISPLAY_NAME, displayName);  
  137.                 }  
  138.                 //插入姓  
  139.                 if (!Utils.isEmpty(familyName)) {  
  140.                     tempBuilder.withValue(StructuredName.FAMILY_NAME, familyName);  
  141.                 }  
  142.                 //插入中间名  
  143.                 if (!Utils.isEmpty(middleName)) {  
  144.                     tempBuilder.withValue(StructuredName.MIDDLE_NAME, middleName);  
  145.                 }  
  146.                 //插入名  
  147.                 if (!Utils.isEmpty(givenName)) {  
  148.                     tempBuilder.withValue(StructuredName.GIVEN_NAME, givenName);  
  149.                 }  
  150.                 //插入前缀  
  151.                 if (!Utils.isEmpty(prefix)) {  
  152.                     tempBuilder.withValue(StructuredName.PREFIX, prefix);  
  153.                 }  
  154.                 //插入后缀  
  155.                 if (!Utils.isEmpty(suffix)) {  
  156.                     tempBuilder.withValue(StructuredName.SUFFIX, suffix);  
  157.                 }  
  158.                 //插入 全拼音  
  159.                 if (!Utils.isEmpty(phoneticName)) {  
  160.                     tempBuilder.withValue(StructuredName.PHONETIC_NAME, phoneticName);  
  161.                 }  
  162.                 //插入  姓拼音  
  163.                 if (!Utils.isEmpty(phoneticFamilyName)) {  
  164.                     tempBuilder.withValue(StructuredName.PHONETIC_FAMILY_NAME, phoneticFamilyName);  
  165.                 }  
  166.                 //插入中间名拼音  
  167.                 if (!Utils.isEmpty(phoneticMiddleName)) {  
  168.                     tempBuilder.withValue(StructuredName.PHONETIC_MIDDLE_NAME, phoneticMiddleName);  
  169.                 }  
  170.                 //插入名拼音  
  171.                 if (!Utils.isEmpty(phoneticGivenName)) {  
  172.                     tempBuilder.withValue(StructuredName.PHONETIC_GIVEN_NAME, phoneticGivenName);  
  173.                 }  
  174.                 ops.add(tempBuilder.build());  
  175.             }  
  176.             //插入昵称  
  177.             if (!Utils.isEmpty(nickName)) {  
  178.                 op = ContentProviderOperation.newInsert(uri)  
  179.                         .withValueBackReference(Data.RAW_CONTACT_ID, rawIndex)  
  180.                         .withValue(Data.MIMETYPE, Nickname.CONTENT_ITEM_TYPE)  
  181.                         .withValue(Nickname.NAME, nickName)  
  182.                         .withYieldAllowed(true)  
  183.                         .build();  
  184.                 ops.add(op);  
  185.             }  
  186.             //插入生日  
  187.             if (!Utils.isEmpty(birthday) || !Utils.isEmpty(anniversary)) {  
  188.                 Builder tempBuilder = ContentProviderOperation.newInsert(uri)  
  189.                         .withValueBackReference(Data.RAW_CONTACT_ID, rawIndex)  
  190.                         .withValue(Data.MIMETYPE, Event.CONTENT_ITEM_TYPE)  
  191.                         .withValue(Event.TYPE, Event.TYPE_BIRTHDAY)  
  192.                         .withYieldAllowed(true);  
  193.                 //插入生日  
  194.                 if (!Utils.isEmpty(anniversary)) {  
  195.                     tempBuilder.withValue(Event.START_DATE, birthday);  
  196.                 }  
  197.                 //插入周年纪念日  
  198.                 if (!Utils.isEmpty(anniversary)) {  
  199.                     tempBuilder.withValue(Event.START_DATE, anniversary);  
  200.                 }  
  201.                 ops.add(tempBuilder.build());  
  202.             }  
  203.               
  204.             //插入备注  
  205.             if (!Utils.isEmpty(note)) {  
  206.                 op = ContentProviderOperation.newInsert(uri)  
  207.                         .withValueBackReference(Data.RAW_CONTACT_ID, rawIndex)  
  208.                         .withValue(Data.MIMETYPE, Note.CONTENT_ITEM_TYPE)  
  209.                         .withValue(Note.NOTE, note)  
  210.                         .withYieldAllowed(true)  
  211.                         .build();  
  212.                 ops.add(op);  
  213.             }  
  214.             //插入组织,公司  
  215.             if (!Utils.isEmpty(company) || !Utils.isEmpty(department) || !Utils.isEmpty(job)) {  
  216.                 Builder tempBuilder = ContentProviderOperation.newInsert(uri)  
  217.                         .withValueBackReference(Data.RAW_CONTACT_ID, rawIndex)  
  218.                         .withValue(Data.MIMETYPE, Organization.CONTENT_ITEM_TYPE)  
  219.                         .withValue(Organization.TYPE, Organization.TYPE_WORK)  
  220.                         .withYieldAllowed(true);  
  221.                 //插入公司  
  222.                 if (!Utils.isEmpty(company)) {  
  223.                     tempBuilder.withValue(Organization.COMPANY, company);  
  224.                 }  
  225.                 //插入部门  
  226.                 if (!Utils.isEmpty(department)) {  
  227.                     tempBuilder.withValue(Organization.DEPARTMENT, department);  
  228.                 }  
  229.                 //插入工作  
  230.                 if (!Utils.isEmpty(job)) {  
  231.                     tempBuilder.withValue(Organization.TITLE, job);  
  232.                 }  
  233.                 ops.add(tempBuilder.build());  
  234.             }  
  235.               
  236.             if (!Utils.isEmpty(phones)) {  
  237.                 //插入电话号码  
  238.                 for (String key : phones.keySet()) {  
  239.                     if (!Utils.isEmpty(phones.get(key))) {  
  240.                         builder = ContentProviderOperation.newInsert(uri);  
  241.                         builder.withValueBackReference(Data.RAW_CONTACT_ID, rawIndex)  
  242.                             .withValue(Data.MIMETYPE, Phone.CONTENT_ITEM_TYPE)  
  243.                             .withValue(Phone.NUMBER, phones.get(key).toString())  
  244.                             .withValue(Phone.LABEL, "手机号")  
  245.                             .withYieldAllowed(true);  
  246.                         String temp = key.split("_")[0];  
  247.                           
  248.                         if(temp.equalsIgnoreCase("mobile")) {//如果是手机号码  
  249.                             builder.withValue(Phone.TYPE, Phone.TYPE_MOBILE);  
  250.                         } else if(temp.equalsIgnoreCase("work")) {//如果是公司电话  
  251.                             builder.withValue(Phone.TYPE, Phone.TYPE_WORK);  
  252.                         } else if(temp.equalsIgnoreCase("workMobile")) {//如果是工作手机  
  253.                             builder.withValue(Phone.TYPE, Phone.TYPE_WORK_MOBILE);  
  254.                         } else if(temp.equalsIgnoreCase("workPager")) {//如果是工作寻呼机  
  255.                             builder.withValue(Phone.TYPE, Phone.TYPE_WORK_PAGER);  
  256.                         } else if(temp.equalsIgnoreCase("faxWork")) {//如果是公司传真号码  
  257.                             builder.withValue(Phone.TYPE, Phone.TYPE_FAX_WORK);  
  258.                         } else if(temp.equalsIgnoreCase("home")) {//如果是家庭电话  
  259.                             builder.withValue(Phone.TYPE, Phone.TYPE_HOME);  
  260.                         } else if(temp.equalsIgnoreCase("faxHome")) {//如果是家庭传真  
  261.                             builder.withValue(Phone.TYPE, Phone.TYPE_FAX_HOME);  
  262.                         } else if(temp.equalsIgnoreCase("pager")) {//如果是寻呼机  
  263.                             builder.withValue(Phone.TYPE, Phone.TYPE_PAGER);  
  264.                         } else if(temp.equalsIgnoreCase("callback")) {//如果是回拨号码  
  265.                             builder.withValue(Phone.TYPE, Phone.TYPE_CALLBACK);  
  266.                         } else if(temp.equalsIgnoreCase("companyMain")) {//如果是公司总机  
  267.                             builder.withValue(Phone.TYPE, Phone.TYPE_COMPANY_MAIN);  
  268.                         } else if(temp.equalsIgnoreCase("car")) {//如果是车载电话  
  269.                             builder.withValue(Phone.TYPE, Phone.TYPE_CAR);  
  270.                         } else if(temp.equalsIgnoreCase("isdn")) {//如果是ISDN   
  271.                             builder.withValue(Phone.TYPE, Phone.TYPE_ISDN);  
  272.                         } else if(temp.equalsIgnoreCase("main")) {//如果是总机  
  273.                             builder.withValue(Phone.TYPE, Phone.TYPE_MAIN);  
  274.                         } else if(temp.equalsIgnoreCase("radio")) {//如果是无线装置  
  275.                             builder.withValue(Phone.TYPE, Phone.TYPE_RADIO);  
  276.                         } else if(temp.equalsIgnoreCase("telex")) {//如果是电报  
  277.                             builder.withValue(Phone.TYPE, Phone.TYPE_TELEX);  
  278.                         } else if(temp.equalsIgnoreCase("ttyTdd")) {//如果是TTY_TDD  
  279.                             builder.withValue(Phone.TYPE, Phone.TYPE_TTY_TDD);  
  280.                         } else if(temp.equalsIgnoreCase("assistant")) {//如果是助理  
  281.                             builder.withValue(Phone.TYPE, Phone.TYPE_ASSISTANT);  
  282.                         } else if(temp.equalsIgnoreCase("mms")) {//如果是彩信  
  283.                             builder.withValue(Phone.TYPE, Phone.TYPE_MMS);  
  284.                         } else {//其他  
  285.                             builder.withValue(Phone.TYPE, Phone.TYPE_OTHER);  
  286.                         }  
  287.                           
  288.                         ops.add(builder.build());  
  289.                     }  
  290.                 }  
  291.             }  
  292.             //插入电子邮件  
  293.             if (!Utils.isEmpty(emails)) {  
  294.                 for (String key : emails.keySet()) {  
  295.                     if (!Utils.isEmpty(emails.get(key))) {  
  296.                         builder = ContentProviderOperation.newInsert(uri);  
  297.                         builder.withValueBackReference(Data.RAW_CONTACT_ID, rawIndex)  
  298.                             .withValue(Data.MIMETYPE, Email.CONTENT_ITEM_TYPE)  
  299.                             .withValue(Email.DATA, emails.get(key).toString())  
  300.                             .withYieldAllowed(true);  
  301.                         String temp = key.split("_")[0];  
  302.                           
  303.                         if(temp.equalsIgnoreCase("home")) {//如果是家庭邮件  
  304.                             builder.withValue(Email.TYPE, Email.TYPE_HOME);  
  305.                         } else if(temp.equalsIgnoreCase("work")) {//如果是公司邮件  
  306.                             builder.withValue(Email.TYPE, Email.TYPE_WORK);  
  307.                         } else if(temp.equalsIgnoreCase("custom")) {//如果是自定义邮件地址  
  308.                             builder.withValue(Email.TYPE, Email.TYPE_CUSTOM);  
  309.                         } else if(temp.equalsIgnoreCase("mobile")) {//如果是手机邮件地址  
  310.                             builder.withValue(Email.TYPE, Email.TYPE_MOBILE);  
  311.                         } else {//其他  
  312.                             builder.withValue(Email.TYPE, Email.TYPE_OTHER);  
  313.                         }  
  314.                         ops.add(builder.build());  
  315.                     }  
  316.                 }  
  317.             }  
  318.             //插入地址  
  319.             if (!Utils.isEmpty(address)) {  
  320.                 for (String key : address.keySet()) {  
  321.                     if (!Utils.isEmpty(address.get(key))) {  
  322.                         builder = ContentProviderOperation.newInsert(uri);  
  323.                         builder.withValueBackReference(Data.RAW_CONTACT_ID, rawIndex)  
  324.                             .withValue(Data.MIMETYPE, StructuredPostal.CONTENT_ITEM_TYPE)  
  325.                             .withValue(StructuredPostal.FORMATTED_ADDRESS, address.get(key).toString())  
  326.                             .withYieldAllowed(true);  
  327.                         String temp = key.split("_")[0];  
  328.                         if(temp.equalsIgnoreCase("home")) {//如果是家庭地址  
  329.                             builder.withValue(StructuredPostal.TYPE, StructuredPostal.TYPE_HOME);  
  330.                         } else if(temp.equalsIgnoreCase("work")) {//如果是公司地址  
  331.                             builder.withValue(StructuredPostal.TYPE, StructuredPostal.TYPE_WORK);  
  332.                         } else if(temp.equalsIgnoreCase("custom")) {//如果是自定义地址  
  333.                             builder.withValue(StructuredPostal.TYPE, StructuredPostal.TYPE_CUSTOM);  
  334.                         } else {//其他  
  335.                             builder.withValue(StructuredPostal.TYPE, StructuredPostal.TYPE_OTHER);  
  336.                         }  
  337.                         ops.add(builder.build());  
  338.                     }  
  339.                 }  
  340.             }  
  341.             //插入即时消息ims  
  342.             if (!Utils.isEmpty(ims)) {  
  343.                 for (String key : ims.keySet()) {  
  344.                     if (!Utils.isEmpty(ims.get(key))) {  
  345.                         builder = ContentProviderOperation.newInsert(uri);  
  346.                         builder.withValueBackReference(Data.RAW_CONTACT_ID, rawIndex)  
  347.                             .withValue(Data.MIMETYPE, Im.CONTENT_ITEM_TYPE)  
  348.                             .withValue(Im.DATA, ims.get(key).toString())  
  349.                             .withYieldAllowed(true);  
  350.                         String temp = key.split("_")[0];  
  351.                         if(temp.equalsIgnoreCase("aim")) {//如果是aim  
  352.                             builder.withValue(Im.PROTOCOL, Im.PROTOCOL_AIM);  
  353.                         } else if(temp.equalsIgnoreCase("msn")) {//如果是msn  
  354.                             builder.withValue(Im.PROTOCOL, Im.PROTOCOL_MSN);  
  355.                         } else if(temp.equalsIgnoreCase("qq")) {//如果是qq  
  356.                             builder.withValue(Im.PROTOCOL, Im.PROTOCOL_QQ);  
  357.                         } else if(temp.equalsIgnoreCase("yahoo")) {//如果是yahoo  
  358.                             builder.withValue(Im.PROTOCOL, Im.PROTOCOL_YAHOO);  
  359.                         } else if(temp.equalsIgnoreCase("custom")) {//如果是custom  
  360.                             builder.withValue(Im.PROTOCOL, Im.PROTOCOL_CUSTOM);  
  361.                         } else if(temp.equalsIgnoreCase("googleTalk")) {//如果是googleTalk  
  362.                             builder.withValue(Im.PROTOCOL, Im.PROTOCOL_GOOGLE_TALK);  
  363.                         } else if(temp.equalsIgnoreCase("icq")) {//如果icq  
  364.                             builder.withValue(Im.PROTOCOL, Im.PROTOCOL_ICQ);  
  365.                         } else if(temp.equalsIgnoreCase("jabber")) {//如果jabber  
  366.                             builder.withValue(Im.PROTOCOL, Im.PROTOCOL_JABBER);  
  367.                         } else if(temp.equalsIgnoreCase("netmeeting")) {//如果netmeeting  
  368.                             builder.withValue(Im.PROTOCOL, Im.PROTOCOL_NETMEETING);  
  369.                         } else if(temp.equalsIgnoreCase("skype")) {//如果skype  
  370.                             builder.withValue(Im.PROTOCOL, Im.PROTOCOL_SKYPE);  
  371.                         } else {//其他  
  372.                             builder.withValue(StructuredPostal.TYPE, StructuredPostal.TYPE_OTHER);  
  373.                         }  
  374.                         ops.add(builder.build());  
  375.                     }  
  376.                 }  
  377.             }  
  378.               
  379.             //插入网站地址 urls  
  380.             if (!Utils.isEmpty(urls)) {  
  381.                 for (String key : urls.keySet()) {  
  382.                     if (!Utils.isEmpty(urls.get(key))) {  
  383.                         builder = ContentProviderOperation.newInsert(uri);  
  384.                         builder.withValueBackReference(Data.RAW_CONTACT_ID, rawIndex)  
  385.                             .withValue(Data.MIMETYPE, Website.CONTENT_ITEM_TYPE)  
  386.                             .withValue(Website.URL, urls.get(key).toString())  
  387.                             .withYieldAllowed(true);  
  388.                         String temp = key.split("_")[0];  
  389.                         if(temp.equalsIgnoreCase("custom")) {//如果是custom web地址  
  390.                             builder.withValue(Website.TYPE, Website.TYPE_CUSTOM);  
  391.                         } else if(temp.equalsIgnoreCase("home")) {//如果是home web地址  
  392.                             builder.withValue(Website.TYPE, Website.TYPE_HOME);  
  393.                         } else if(temp.equalsIgnoreCase("homePage")) {//如果是homePage web地址  
  394.                             builder.withValue(Website.TYPE, Website.TYPE_HOMEPAGE);  
  395.                         } else if(temp.equalsIgnoreCase("work")) {//如果是work web地址  
  396.                             builder.withValue(Website.TYPE, Website.TYPE_WORK);  
  397.                         } else if(temp.equalsIgnoreCase("ftp")) {//如果是ftp web地址  
  398.                             builder.withValue(Website.TYPE, Website.TYPE_FTP);  
  399.                         } else if(temp.equalsIgnoreCase("blog")) {//如果是blog web地址  
  400.                             builder.withValue(Website.TYPE, Website.TYPE_BLOG);  
  401.                         } else {//其他  
  402.                             builder.withValue(StructuredPostal.TYPE, StructuredPostal.TYPE_OTHER);  
  403.                         }  
  404.                         ops.add(builder.build());  
  405.                     }  
  406.                 }  
  407.             }  
  408.               
  409.             if (!Utils.isEmpty(groups)) {  
  410.                 //循环组,先判断是否组存在,如果不存在,创建组  
  411.                 for (String key : groups.keySet()) {  
  412.                     String val = groups.get(key).toString();  
  413.                     long id = -1;  
  414.                     //如果key是个id,表示组已经存在  
  415.                     if (Utils.isNumber(val)) {  
  416.                         id = Long.parseLong(val);  
  417.                     } else if (!Utils.isEmpty(val)) {  
  418.                         //如果组不存在,判断组的名字是否为空,不为空,查询是否存在,不存在创建  
  419.                         id = createGroup(val);  
  420.                     }  
  421.                     if (id != -1) {  
  422.                         builder = ContentProviderOperation.newInsert(uri);  
  423.                         builder.withValueBackReference(GroupMembership.RAW_CONTACT_ID, rawIndex);  
  424.                         // 给组添加成员(groupId, personId)  
  425.                         builder.withValue(Data.MIMETYPE, GroupMembership.CONTENT_ITEM_TYPE)  
  426.                                 .withValue(GroupMembership.GROUP_ROW_ID, id)  
  427.                                 .withYieldAllowed(true)  
  428.                                 .build();  
  429.                         ops.add(builder.build());  
  430.                     }  
  431.                 }  
  432.             }  
  433.             Log.i(Const.APPTAG, ">>==" +  ops.toString() );  
  434.             //批量执行插入  
  435.             try {  
  436.                 ContentProviderResult[] results = resolver.applyBatch(ContactsContract.AUTHORITY, ops);  
  437.                 //插入成功返回的Uri集合  
  438.                 Map<Long, String> uris = new HashMap<Long, String>();  
  439.                 for (ContentProviderResult result : results) {  
  440.                     Log.i(Const.APPTAG, result.toString());  
  441.                     if (result.uri != null) {  
  442.                         uris.put(ContentUris.parseId(result.uri), result.uri.toString());  
  443.                     }  
  444.                 }  
  445.                 if (uris.size() > 0) {  
  446.                     addResult.put("result""1");  
  447.                     addResult.put("obj", uris);  
  448.                 }  
  449.             } catch (Exception e) {  
  450.                 Log.i(Const.APPTAG, e.getMessage());  
  451.                 addResult.put("result""-1");  
  452.                 addResult.put("obj""插入失败:" + e.getMessage());  
  453.             }  
  454.         }  
  455.           
  456.         if (addResult.size() == 0) {  
  457.             addResult.put("result""0");  
  458.             addResult.put("obj""无效插入,联系人信息不完整!");  
  459.         }  
  460.         return addResult;  
  461.     }  
  462.       
  463.     /** 
  464.      * 根据联系人id查询联系人详细信息 
  465.      *  
  466.      * @param contactId 
  467.      * @return HashMap<String, String> 
  468.      *         <p> 
  469.      *         查询的所有字段:data_version, phonetic_name, data_set, phonetic_name_style, contact_id, lookup, data12, data11, data10, 
  470.      *         mimetype, data15, data14, data13, display_name_source, photo_uri, data_sync1, data_sync3, data_sync2, contact_chat_capability, 
  471.      *         data_sync4, account_type, account_type_and_data_set, custom_ringtone, photo_file_id, has_phone_number, nickname, 
  472.      *         status, data1, chat_capability, data4, data5, data2, data3, data8, data9, data6, group_sourceid, account_name, data7, 
  473.      *         display_name, raw_contact_is_user_profile, in_visible_group, display_name_alt, company, contact_account_type, 
  474.      *         contact_status_res_package, is_primary, contact_status_ts,  raw_contact_id, times_contacted, contact_status, 
  475.      *         status_res_package, status_icon, contact_status_icon, version, mode, last_time_contacted, res_package, _id, name_verified, 
  476.      *         dirty, status_ts, is_super_primary, photo_thumb_uri, photo_id, send_to_voicemail, name_raw_contact_id, contact_status_label, 
  477.      *         status_label, sort_key_alt, starred, sort_key, contact_presence, sourceid 
  478.      *         </p> 
  479.      *         <p> 
  480.      *         Phone.TYPE: TYPE_HOME = 1;      TYPE_MOBILE = 2;        TYPE_WORK = 3; 
  481.      *                     TYPE_FAX_WORK = 4;  TYPE_FAX_HOME = 5;      TYPE_PAGER = 6;  
  482.      *                     TYPE_OTHER = 7;     TYPE_CALLBACK = 8;      TYPE_CAR = 9;  
  483.      *                 TYPE_COMPANY_MAIN = 10; TYPE_ISDN = 11;         TYPE_MAIN = 12;  
  484.      *                 TYPE_OTHER_FAX = 13;    TYPE_RADIO = 14;        TYPE_TELEX = 15;  
  485.      *                 TYPE_TTY_TDD = 16;      TYPE_WORK_MOBILE = 17;  TYPE_WORK_PAGER = 18;  
  486.      *                 TYPE_ASSISTANT = 19;    TYPE_MMS = 20; 
  487.      *         </p> 
  488.      */  
  489.     public HashMap<String, Object> getContactById(String contactId) {  
  490.         HashMap<String, Object> contact = new HashMap<String, Object>();  
  491.           
  492.         Cursor ctCursor = resolver.query(Contacts.CONTENT_URI, new String[]{   
  493.                 Contacts._ID,   
  494. //              Contacts.DISPLAY_NAME,   
  495.                 Contacts.SORT_KEY_PRIMARY,  
  496.                 Contacts.LAST_TIME_CONTACTED,  
  497.                 }, Contacts._ID + "=" + contactId, nullnull);  
  498.           
  499.         while (ctCursor.moveToNext()) {  
  500.             String id = ctCursor.getString(0);  
  501. //          String displayName = ctCursor.getString(1);  
  502.             String sortKey = ctCursor.getString(1);  
  503.             String lastTime = ctCursor.getString(2);  
  504.               
  505.             contact.put("id", id);  
  506.             contact.put("sortKey", sortKey);  
  507. //          contact.put("displayName", displayName);  
  508.               
  509.             contact.put("lastTime", lastTime);  
  510.         }  
  511.         ctCursor.close();  
  512.           
  513.         getContactsData(contactId, contact);  
  514.         return contact;  
  515.     }  
  516.   
  517.     /** 
  518.      * 获取联系人详细信息(电话、email、im、网站、地址、分组) 
  519.      * @param contactId 
  520.      * @param contact 
  521.      */  
  522.     private void getContactsData(String contactId, Map<String, Object> contact) {  
  523.         HashMap<String, Object> phones = new HashMap<String, Object>();  
  524.         HashMap<String, Object> emails = new HashMap<String, Object>();  
  525.         HashMap<String, Object> address = new HashMap<String, Object>();  
  526.         HashMap<String, Object> ims = new HashMap<String, Object>();  
  527.         HashMap<String, Object> urls = new HashMap<String, Object>();  
  528.         HashMap<String, Object> groups = new HashMap<String, Object>();  
  529.           
  530.         //如果要获得data表中某个id对应的数据,则URI为content://com.android.contacts/contacts/#/data  
  531.         Uri contactsUri = ContentUris.withAppendedId(Contacts.CONTENT_URI, Long.parseLong(contactId));  
  532.         Uri uri = Uri.withAppendedPath(contactsUri, Contacts.Data.CONTENT_DIRECTORY);  
  533.           
  534.          //Data表: data1存储各个记录的总数据,mimetype存放记录的类型,如电话、email等      
  535.         //PHOTO_FILE_ID = DATA14; PHOTO = DATA15; 照片头像  
  536.         //new String[] { Data._ID, Data.DATA1, Data.DATA15, Data.MIMETYPE }  
  537.         Cursor cursor = resolver.query(uri, nullnullnullnull);  
  538.           
  539.         //查询联系人个人信息  
  540.         while (cursor.moveToNext()) {  
  541.             String id = cursor.getString(cursor.getColumnIndex(Data._ID));  
  542.             String mimeType = cursor.getString(cursor.getColumnIndex(Data.MIMETYPE));  
  543.             String data1 = cursor.getString(cursor.getColumnIndex(Data.DATA1));  
  544.             int data2 = cursor.getInt(cursor.getColumnIndex(Data.DATA2));  
  545.               
  546.             // 这些类都在  android.provider.ContactsContract.CommonDataKinds 下  
  547.             // vnd.android.cursor.item/name 如果是姓名  
  548.             if (mimeType.equals(StructuredName.CONTENT_ITEM_TYPE)) {  
  549.                 String familyName = cursor.getString(cursor.getColumnIndex(StructuredName.FAMILY_NAME));  
  550.                 String middleName = cursor.getString(cursor.getColumnIndex(StructuredName.MIDDLE_NAME));  
  551.                 String givenName = cursor.getString(cursor.getColumnIndex(StructuredName.GIVEN_NAME));  
  552.                 String prefix = cursor.getString(cursor.getColumnIndex(StructuredName.PREFIX));  
  553.                 String suffix = cursor.getString(cursor.getColumnIndex(StructuredName.SUFFIX));  
  554.                 String phoneticName = cursor.getString(cursor.getColumnIndex(StructuredName.PHONETIC_NAME));  
  555.                 String phoneticFamilyName = cursor.getString(cursor.getColumnIndex(StructuredName.PHONETIC_FAMILY_NAME));  
  556.                 String phoneticMiddleName = cursor.getString(cursor.getColumnIndex(StructuredName.PHONETIC_MIDDLE_NAME));  
  557.                 String phoneticGivenName = cursor.getString(cursor.getColumnIndex(StructuredName.PHONETIC_GIVEN_NAME));  
  558.                   
  559.                 contact.put("diplayName", data1);//显示名称(前缀+中缀+姓+中间名+名+后缀)  
  560.                 contact.put("familyName", familyName);//姓  
  561.                 contact.put("middleName", middleName);//中间名  
  562.                 contact.put("givenName", givenName);//名  
  563.                 contact.put("prefix", prefix);//前缀  
  564.                 contact.put("suffix", suffix);//后缀  
  565.                 contact.put("phoneticName", phoneticName);//全拼音  
  566.                 contact.put("phoneticFamilyName", phoneticFamilyName);//姓拼音  
  567.                 contact.put("phoneticMiddleName", phoneticMiddleName);//中间名拼音  
  568.                 contact.put("phoneticGivenName", phoneticGivenName);//名拼音  
  569.                 if (Utils.isEmpty(data1)) {  
  570.                     data1 = "";  
  571.                 }  
  572.                 contact.put("phoneticFullname", Utils.getPinYinHeadChar(data1));  
  573.                   
  574.             }// 获取昵称信息  
  575.             else if (mimeType.equals(Nickname.CONTENT_ITEM_TYPE)) {  
  576.                     String nickName = cursor.getString(cursor.getColumnIndex(Nickname.NAME));  
  577.                     contact.put("nickName", nickName);  
  578.             }//vnd.android.cursor.item/phone_v2 如果是电话   
  579.             else if (mimeType.equals(Phone.CONTENT_ITEM_TYPE)) {  
  580.                 switch (data2) {  
  581.                     case Phone.TYPE_MOBILE://手机号码  
  582.                         phones.put("mobile_" + id, data1);  
  583.                         break;  
  584.                     case Phone.TYPE_WORK://公司电话  
  585.                         phones.put("work_" + id, data1);  
  586.                         break;  
  587.                     case Phone.TYPE_WORK_MOBILE://工作手机  
  588.                         phones.put("workMobile_" + id, data1);  
  589.                         break;  
  590.                     case Phone.TYPE_WORK_PAGER://工作寻呼机  
  591.                         phones.put("workPager_" + id, data1);  
  592.                         break;  
  593.                     case Phone.TYPE_FAX_WORK://工作传真  
  594.                         phones.put("faxWork_" + id, data1);  
  595.                         break;  
  596.                     case Phone.TYPE_HOME://家庭电话  
  597.                         phones.put("home_" + id, data1);  
  598.                         break;  
  599.                     case Phone.TYPE_FAX_HOME://家庭传真  
  600.                         phones.put("faxHome_" + id, data1);  
  601.                         break;  
  602.                     case Phone.TYPE_PAGER://寻呼机  
  603.                         phones.put("pager_" + id, data1);  
  604.                         break;  
  605.                     case Phone.TYPE_CALLBACK://回拨号码  
  606.                         phones.put("callback_" + id, data1);  
  607.                         break;  
  608.                     case Phone.TYPE_COMPANY_MAIN://公司总机  
  609.                         phones.put("companyMain_" + id, data1);  
  610.                         break;  
  611.                     case Phone.TYPE_CAR://车载电话  
  612.                         phones.put("car_" + id, data1);  
  613.                         break;  
  614.                     case Phone.TYPE_ISDN://ISDN   
  615.                         phones.put("isdn_" + id, data1);  
  616.                         break;  
  617.                     case Phone.TYPE_MAIN://总机     
  618.                         phones.put("main_" + id, data1);  
  619.                         break;  
  620.                     case Phone.TYPE_RADIO://无线装置      
  621.                         phones.put("radio_" + id, data1);  
  622.                         break;  
  623.                     case Phone.TYPE_TELEX://电报    
  624.                         phones.put("telex_" + id, data1);  
  625.                         break;  
  626.                     case Phone.TYPE_TTY_TDD://TTY_TDD  
  627.                         phones.put("ttyTdd_" + id, data1);  
  628.                         break;  
  629.                     case Phone.TYPE_ASSISTANT:// 助理  
  630.                         phones.put("assistant_" + id, data1);  
  631.                         break;  
  632.                     case Phone.TYPE_MMS://彩信  
  633.                         phones.put("mms_" + id, data1);  
  634.                         break;  
  635.                     default://其他号码  
  636.                         phones.put("other_" + id, data1);  
  637.                         break;  
  638.                 }  
  639.             }//vnd.android.cursor.item/email_v2 如果是电子邮件 ,怎么会保存在 家用字段  
  640.             else if (mimeType.equals(Email.CONTENT_ITEM_TYPE)) {  
  641.                   
  642.                 switch (data2) {  
  643.                     case Email.TYPE_WORK://工作邮件  
  644.                         emails.put("work_" + id, data1);  
  645.                         break;  
  646.                     case Email.TYPE_HOME://家庭邮件  
  647.                         emails.put("home_" + id, data1);  
  648.                         break;  
  649.                     case Email.TYPE_CUSTOM://自定义邮件地址  
  650.                         emails.put("custom_" + id, data1);  
  651.                         break;  
  652.                     case Email.TYPE_MOBILE://手机邮件地址  
  653.                         emails.put("mobile_" + id, data1);  
  654.                         break;  
  655.                     default://其他   
  656.                         emails.put("other_" + id, data1);  
  657.                         break;  
  658.                 }  
  659.             }//vnd.android.cursor.item/email_v2如果是地址  
  660.             else if (mimeType.equals(StructuredPostal.CONTENT_ITEM_TYPE)) {  
  661.                 switch (data2) {  
  662.                     case StructuredPostal.TYPE_HOME://家庭地址  
  663.                         address.put("home_" + id, data1);  
  664.                         break;  
  665.                     case StructuredPostal.TYPE_WORK://工作公司地址  
  666.                         address.put("work_" + id, data1);  
  667.                         break;  
  668.                     case StructuredPostal.TYPE_CUSTOM://自定义地址  
  669.                         address.put("custom_" + id, data1);  
  670.                         break;  
  671.                     default://其他地址  
  672.                         address.put("other_" + id, data1);  
  673.                         break;  
  674.                 }  
  675.               
  676.             }// 获取组织信息  
  677.             else if(mimeType.equals(Organization.CONTENT_ITEM_TYPE)){  
  678.                 // 取出组织类型  
  679.                 int orgType = cursor.getInt(cursor.getColumnIndex(Organization.TYPE));  
  680.                 // 单位  
  681. //              if (orgType == Organization.TYPE_CUSTOM) {  
  682.                 if (orgType == Organization.TYPE_WORK) {  
  683.                     String company = cursor.getString(cursor.getColumnIndex(Organization.COMPANY));  
  684.                     contact.put("company", company);  
  685.                     String job = cursor.getString(cursor.getColumnIndex(Organization.TITLE));  
  686.                     contact.put("job", job);  
  687.                     String department = cursor.getString(cursor.getColumnIndex(Organization.DEPARTMENT));  
  688.                     contact.put("department", department);  
  689.                 }  
  690.               
  691.             }//获取生日  
  692.             else if(mimeType.equals(Event.CONTENT_ITEM_TYPE)){  
  693.                 // 生日  
  694.                 switch (data2) {  
  695.                     case Event.TYPE_BIRTHDAY:  
  696.                         contact.put("birthday", data1);  
  697.                     break;  
  698.                     case Event.TYPE_ANNIVERSARY:  
  699.                         contact.put("anniversary", data1);  
  700.                     break;  
  701. //                  default://其他   
  702. //                      contact.put("otherDate_" + id, data1);  
  703. //                      break;  
  704.                 }  
  705.             }// 获取备注信息  
  706.             else if (mimeType.equals(Note.CONTENT_ITEM_TYPE)) {  
  707.                 String note = cursor.getString(cursor.getColumnIndex(Note.NOTE));  
  708.                 contact.put("note", note);  
  709.             }// 即时消息 ims  
  710.             else if (mimeType.equals(Im.CONTENT_ITEM_TYPE)) {  
  711.                     // 取出即时消息类型  
  712.                     int protocal = cursor.getInt(cursor.getColumnIndex(Im.PROTOCOL));  
  713.                     switch (protocal) {  
  714.                         case Im.PROTOCOL_AIM://aim  
  715.                             ims.put("aim_" + id, data1);  
  716.                             break;  
  717.                         case Im.PROTOCOL_MSN://msn  
  718.                             ims.put("msn_" + id, data1);  
  719.                             break;  
  720.                         case Im.PROTOCOL_QQ://QQ  
  721.                             ims.put("qq_" + id, data1);  
  722.                             break;  
  723.                         case Im.PROTOCOL_YAHOO://YAHOO  
  724.                             ims.put("yahoo_" + id, data1);  
  725.                             break;  
  726.                         case Im.PROTOCOL_CUSTOM://CUSTOM  
  727.                             ims.put("custom_" + id, data1);  
  728.                         case Im.PROTOCOL_GOOGLE_TALK://GOOGLE_TALK  
  729.                             ims.put("googleTalk_" + id, data1);  
  730.                             break;  
  731.                         case Im.PROTOCOL_ICQ://ICQ  
  732.                             ims.put("icq_" + id, data1);  
  733.                             break;  
  734.                         case Im.PROTOCOL_JABBER://JABBER  
  735.                             ims.put("jabber_" + id, data1);  
  736.                             break;  
  737.                         case Im.PROTOCOL_NETMEETING://NETMEETING  
  738.                             ims.put("netmeeting_" + id, data1);  
  739.                             break;  
  740.                         case Im.PROTOCOL_SKYPE://SKYPE  
  741.                             ims.put("skype_" + id, data1);  
  742.                             break;  
  743.                         default://其他   
  744.                             ims.put("other_" + id, data1);  
  745.                             break;  
  746.                     }  
  747.                 } // 获取网站信息  
  748.                 else if (mimeType.equals(Website.CONTENT_ITEM_TYPE)) {  
  749.                     // 取出网站类型  
  750.                     int webType = cursor.getInt(cursor.getColumnIndex(Website.TYPE));  
  751.                     switch (webType) {  
  752.                         case Website.TYPE_CUSTOM://CUSTOM  
  753.                             urls.put("custom_" + id, data1);  
  754.                             break;  
  755.                         case Website.TYPE_HOME://HOME  
  756.                             urls.put("home_" + id, data1);  
  757.                             break;  
  758.                         case  Website.TYPE_HOMEPAGE://HOMEPAGE  
  759.                             urls.put("homePage_" + id, data1);  
  760.                             break;  
  761.                         case Website.TYPE_WORK://WORK  
  762.                             urls.put("work_" + id, data1);  
  763.                             break;  
  764.                         case Website.TYPE_FTP://FTP  
  765.                             urls.put("ftp_" + id, data1);  
  766.                             break;  
  767.                         case Website.TYPE_BLOG://BLOG博客  
  768.                             urls.put("blog_" + id, data1);  
  769.                             break;  
  770.                         default://其他   
  771.                             urls.put("other_" + id, data1);  
  772.                             break;  
  773.                     }  
  774.                 }  
  775. //          vnd.android.cursor.item/photo 如果是照片  
  776. //          } else if (mimeType.equals(Photo.CONTENT_ITEM_TYPE)) {  
  777. //              // Photo.PHOTO = Data.DATA15  
  778. //                
  779. //              byte[] data = cursor.getBlob(cursor.getColumnIndex(Photo.PHOTO));  
  780. //              Bitmap bm = BitmapFactory.decodeByteArray(data, 0, data.length);  
  781. //          }  
  782. //          vnd.android.cursor.item/organization如果是组织  
  783. //          else if (mimeType.equals(Organization.CONTENT_ITEM_TYPE)) { }  
  784.         }  
  785.         cursor.close();  
  786.         //如果查询到数据  
  787.         if (contact.size() > 0 || phones.size() > 0 ||  emails.size() > 0 || address.size() > 0  
  788.                 || ims.size() > 0 || urls.size() > 0) {  
  789.             contact.put("contactId", contactId);  
  790.             //查询联系人所在的组  
  791.             Cursor gmsCursor = resolver.query(  
  792.                     Data.CONTENT_URI,   
  793.                     new String[]{ Data._ID, GroupMembership.GROUP_ROW_ID },   
  794.                     GroupMembership.MIMETYPE + "=? and " + Data.RAW_CONTACT_ID + "=?",   
  795.                     new String[]{ GroupMembership.CONTENT_ITEM_TYPE, contactId },  
  796.                     null);  
  797.             while (gmsCursor.moveToNext()) {  
  798.                 int _id = gmsCursor.getInt(0);  
  799.                 int groupId = gmsCursor.getInt(1);  
  800.                 Cursor groupCursor = resolver.query(  
  801.                         Groups.CONTENT_URI,   
  802.                         new String[]{ Groups._ID, Groups.TITLE},   
  803.                         Groups._ID + "=" + groupId,   
  804.                         null,  
  805.                         null);  
  806.                 if(groupCursor.moveToFirst()){  
  807.                     groups.put("title" + _id + "_" + groupId, groupCursor.getString(1));  
  808.         //          groups.put(groups.size() + ":id,title", groupId + "," + groupCursor.getString(1));  
  809.                 }  
  810.                 groupCursor.close();  
  811.             }  
  812.             gmsCursor.close();  
  813.               
  814.             contact.put("groups", groups);  
  815.             contact.put("phones", phones);  
  816.             contact.put("emails", emails);  
  817.             contact.put("addresses", address);  
  818.             contact.put("ims", ims);  
  819.             contact.put("urls", urls);  
  820.         }  
  821.     }  
  822.   
  823.     /** 
  824.      * 查询联系人 
  825.      * @param 姓名模糊查询-根据分组查询-根据电话号码(完全匹配)查询 
  826.      * @param selections[name=v,groupId=v,phone=v] 
  827.      * @return List<Long> contactId 
  828.      */  
  829.     public Set<String> query(Map<String, String> selections){  
  830.         Set<String> ids = new HashSet<String>();  
  831.         String groupId      = null;  
  832.         String displayName  = null;  
  833.         String phone        = null;  
  834.         if (!Utils.isEmpty(selections)) {  
  835.             groupId         = selections.get("groupId");//分组id  
  836.             displayName     = selections.get("displayName");//姓名  
  837.             phone           = selections.get("phoneNumber");//电话  
  838.         }  
  839.           
  840.         Log.i(Const.APPTAG, "查询联系人条件:groupId=" + groupId + ";displayName=" + displayName + ";phone=" + phone);  
  841.         //查询条件为空代表查询所有联系人  
  842.         if (selections == null || selections.size() == 0 ||   
  843.                 (!Utils.isNumber(groupId) && Utils.isEmpty(displayName) && Utils.isEmpty(phone)) ) {  
  844.             //管理联系人的uri  
  845.             Uri uri = Contacts.CONTENT_URI;  
  846.             Cursor cursor = null;  
  847.               
  848.             cursor = resolver.query(uri, new String[]{ Contacts._ID, Contacts.DISPLAY_NAME}, nullnull,    
  849.                     Contacts.SORT_KEY_PRIMARY + " asc");  
  850.             //循环查询结果 cursor  
  851.             while (cursor.moveToNext()) {  
  852.                 ids.add(cursor.getString(cursor.getColumnIndex(Contacts._ID)));  
  853.             }  
  854.             cursor.close();  
  855.         } else {  
  856.             if (groupId != null && Utils.isNumber(groupId)) {  
  857.                 Cursor groupCursor = null;  
  858.                 //根据组id查询关系表  
  859.                 groupCursor = resolver.query(  
  860.                         Data.CONTENT_URI,  
  861.                         new String[] { Data.RAW_CONTACT_ID },  
  862.                         Data.MIMETYPE + "=? AND " + GroupMembership.GROUP_ROW_ID + "=?",  
  863.                         new String[] { GroupMembership.CONTENT_ITEM_TYPE, groupId },   
  864.                         null);  
  865.                 StringBuffer selection = new StringBuffer(Data.RAW_CONTACT_ID + " in(");  
  866.                 //如果有这个组,在组里,根据条件查询联系人  
  867.                 List<String> selectionArgs = new ArrayList<String>();  
  868.                 while (groupCursor.moveToNext()) {  
  869.                     selection.append("?,");  
  870.                     selectionArgs.add(groupCursor.getInt(0) + "");  
  871.                 }  
  872.                 groupCursor.close();  
  873.                 selection = new StringBuffer(selection.substring(0, selection.length() - 1) + ")");  
  874.                    
  875.                 queryContactIds(ids, displayName, phone, selection, selectionArgs);  
  876.             } else {  
  877.                 StringBuffer selection = new StringBuffer();  
  878.                 List<String> selectionArgs = new ArrayList<String>();  
  879.                   
  880.                 queryContactIds(ids, displayName, phone, selection, selectionArgs);  
  881.             }  
  882.               
  883.         }   
  884.         return ids;  
  885.     }  
  886.   
  887.     /** 
  888.      * 根据姓名,电话查询联系人 
  889.      * @param ids 
  890.      * @param name 
  891.      * @param phone 
  892.      * @param selection 
  893.      * @param selectionArgs 
  894.      */  
  895.     private void queryContactIds(Set<String> ids, String name, String phone,  
  896.             StringBuffer selection, List<String> selectionArgs) {  
  897.         if (name != null && !name.equals("")) {  
  898.             selection.append(selection.length() > 0 ? " AND " : "");  
  899.             selection.append(StructuredName.DISPLAY_NAME + " LIKE ? ");  
  900.             selectionArgs.add("%" + name + "%");  
  901.         }  
  902.         if (phone != null && !phone.equals("")) {  
  903.             selection.append(selection.length() > 0 ? " OR " : "");  
  904.             selection.append(Phone.NUMBER + " = ?  ");  
  905.             selectionArgs.add(phone);  
  906.         }  
  907.           
  908.         Log.i(Const.APPTAG, "查询联系人-where:" + selection.toString() + ";val:" + selectionArgs.toString());  
  909.           
  910.         Cursor contactCursor = resolver.query(  
  911.                 Data.CONTENT_URI,  
  912.                 new String[] { Data.RAW_CONTACT_ID, StructuredName.DISPLAY_NAME },  
  913.                 selection.toString(),   
  914.                 selectionArgs.toArray(new String[]{}),  
  915.                 null);  
  916.         while (contactCursor.moveToNext()) {  
  917.             ids.add(contactCursor.getString(contactCursor.getColumnIndex(Data.RAW_CONTACT_ID)));  
  918.         }  
  919.         contactCursor.close();  
  920.     }  
  921.     /** 
  922.      * 获得所有联系人的id  
  923.      * @return List<String> 
  924.      */  
  925.     public List<String> getContactsIds(){  
  926.           
  927.         List<String> ids = new ArrayList<String>();  
  928.           
  929.         Uri uri = Contacts.CONTENT_URI;  
  930.           
  931.         Cursor cursor = resolver.query(uri, new String[]{ Contacts._ID }, nullnullnull);  
  932.         while (cursor.moveToNext()) {  
  933.             ids.add(cursor.getString(0));  
  934.         }  
  935.         cursor.close();  
  936.            
  937.         return ids;  
  938.     }  
  939.     /** 
  940.      * 查询所有联系人(id、姓名、所有电话) 
  941.      * @param luaStateWrapper  
  942.      * @return List<Map<String, Object>> 
  943.      */  
  944.     public List<Map<String, Object>> getContacts(){  
  945.           
  946.         List<Map<String, Object>> listContacts = new ArrayList<Map<String,Object>>();  
  947.           
  948.         Uri uri = Contacts.CONTENT_URI;  
  949.           
  950.         Cursor cursor = resolver.query(uri, new String[]{   
  951.                 Contacts._ID,   
  952. //              Contacts.DISPLAY_NAME,   
  953.                 Contacts.SORT_KEY_PRIMARY,  
  954.                 Contacts.LAST_TIME_CONTACTED,}, nullnullnull);  
  955.           
  956.         Map<String, Object> ct = null;  
  957. //      String displayName = null;  
  958.           
  959.         while (cursor.moveToNext()) {  
  960.             ct = new HashMap<String, Object>();  
  961.             String id = cursor.getString(0);   
  962. //          displayName = cursor.getString(1);  
  963.             String sortKey = cursor.getString(1);  
  964.             String lastTime = cursor.getString(2);  
  965.               
  966.             ct.put("id", id);  
  967. //          ct.put("displayName", displayName);  
  968.             ct.put("sortKey", sortKey);  
  969.             ct.put("lastTime", lastTime);  
  970.               
  971.             listContacts.add(ct);  
  972.         }  
  973.         cursor.close();  
  974.           
  975.         for (Map<String, Object> contact : listContacts) {  
  976.             String contactId = contact.get("contactId").toString();  
  977.             getContactsData(contactId, contact);  
  978.         }  
  979.         return listContacts;  
  980.     }  
  981.       
  982. //  /**  
  983. //   * 根据联系id查询所有的号码  
  984. //   * @param contactId  
  985. //   * @return HashMap<String, Object>  
  986. //   */  
  987. //  public HashMap<String, Object> getPhonesByContactId(String contactId) {  
  988. //      HashMap<String, Object> phones = new HashMap<String, Object>();  
  989. //        
  990. //      //如果要获得data表中某个id对应的数据,则URI为content://com.android.contacts/contacts/#/data  
  991. //      Uri contactsUri = ContentUris.withAppendedId(Contacts.CONTENT_URI, Long.parseLong(contactId));  
  992. //      Uri uri = Uri.withAppendedPath(contactsUri, Contacts.Data.CONTENT_DIRECTORY);  
  993. //        
  994. //      Cursor cursor = resolver.query(uri, null, null, null, null);  
  995. //        
  996. //      //查询联系人个人信息  
  997. //      while (cursor.moveToNext()) {  
  998. //          String id = cursor.getString(cursor.getColumnIndex(Data._ID));  
  999. //          String mimeType = cursor.getString(cursor.getColumnIndex(Data.MIMETYPE));  
  1000. //          String data1 = cursor.getString(cursor.getColumnIndex(Data.DATA1));  
  1001. //          int data2 = cursor.getInt(cursor.getColumnIndex(Data.DATA2));  
  1002. //            
  1003. //          if (mimeType.equals(Phone.CONTENT_ITEM_TYPE)) {  
  1004. //              switch (data2) {  
  1005. //                  case Phone.TYPE_MOBILE://手机号码  
  1006. //                      phones.put("mobile_" + id, data1);  
  1007. //                      break;  
  1008. //                  case Phone.TYPE_WORK://公司电话  
  1009. //                      phones.put("work_" + id, data1);  
  1010. //                      break;  
  1011. //                  case Phone.TYPE_FAX_WORK://工作传真  
  1012. //                      phones.put("faxWork_" + id, data1);  
  1013. //                      break;  
  1014. //                  case Phone.TYPE_HOME://家庭电话  
  1015. //                      phones.put("home_" + id, data1);  
  1016. //                      break;  
  1017. //                  case Phone.TYPE_OTHER://其他号码  
  1018. //                  default:  
  1019. //                      phones.put("other_" + id, data1);  
  1020. //                      break;  
  1021. //              }  
  1022. //          }    
  1023. //      }  
  1024. //      cursor.close();  
  1025. //      return phones;  
  1026. //  }  
  1027. //    
  1028.     /** 
  1029.      * 获取所有的组 
  1030.      * @return 
  1031.      */  
  1032.     public List<HashMap<String, String>> getGroups() {  
  1033.         List<HashMap<String, String>> groups = new ArrayList<HashMap<String,String>>();  
  1034.         Cursor cursor = resolver.query(Groups.CONTENT_URI, nullnullnullnull);  
  1035.         HashMap<String, String> group = new HashMap<String, String>();  
  1036.         while (cursor.moveToNext()) {  
  1037.             int id = cursor.getInt(cursor.getColumnIndex(Groups._ID));  
  1038.             String title = cursor.getString(cursor.getColumnIndex(Groups.TITLE));  
  1039.             group.put("id", id + "");  
  1040.             group.put("title", title);  
  1041.             groups.add(group);  
  1042.         }  
  1043.         cursor.close();  
  1044.         return groups;  
  1045.     }  
  1046.       
  1047.     /** 
  1048.      * 创建组 
  1049.      * @return int 
  1050.      */  
  1051.     public long createGroup(String title) {  
  1052.         if (Utils.isEmpty(title)) {  
  1053.             return -1;  
  1054.         }  
  1055.         long gId = getGroupByTitle(title);  
  1056.         if (gId == -1) {  
  1057.             ContentValues values = new ContentValues();  
  1058.             values.put(Groups.TITLE, title);  
  1059.             Uri uri = resolver.insert(Groups.CONTENT_URI, values);  
  1060.             gId = ContentUris.parseId(uri);  
  1061.         }  
  1062.         return gId;  
  1063.     }  
  1064.     /** 
  1065.      * 根据组的名称查询组 
  1066.      * @return int 
  1067.      */  
  1068.     public int getGroupByTitle(String title) {  
  1069.         int id = -1;  
  1070.         Cursor cursor = resolver.query(  
  1071.                 Groups.CONTENT_URI,   
  1072.                 new String[] { Groups._ID },   
  1073.                 Groups.TITLE + "='" + title + "'",   
  1074.                 nullnull);  
  1075.         if(cursor.moveToNext()) {  
  1076.             id = cursor.getInt(cursor.getColumnIndex(Groups._ID));  
  1077.         }  
  1078.         cursor.close();  
  1079.         return id;  
  1080.     }  
  1081.     /** 
  1082.      * 根据组的id删除组 
  1083.      * @return int 
  1084.      */  
  1085.     public int delGroupById(String selection, String[] ids) {  
  1086.         Uri uri = Uri.parse(Groups.CONTENT_URI + "?" + ContactsContract.CALLER_IS_SYNCADAPTER + "=true");  
  1087.         int i = resolver.delete(  
  1088.                 uri,   
  1089.                 Groups._ID + selection ,   
  1090.                 ids);  
  1091.         return i;  
  1092.     }  
  1093.       
  1094.     /** 
  1095.      * 删除全部联系人 
  1096.      * @return 
  1097.      */  
  1098.     public HashMap<String, Object> delAllContacts() {  
  1099.         ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>();  
  1100.         ContentProviderOperation op = null;  
  1101.         Uri uri = null;  
  1102.         HashMap<String, Object> delResult = new HashMap<String, Object>();  
  1103.         int num = 0;//删除影响的行数  
  1104.         resolver.delete(Uri.parse(ContactsContract.RawContacts.CONTENT_URI.toString() + "?"   
  1105.                 + ContactsContract.CALLER_IS_SYNCADAPTER + "=true"),   
  1106.                 ContactsContract.RawContacts._ID + ">0"null);  
  1107.         //删除Data表的数据  
  1108.         uri = Uri.parse(Data.CONTENT_URI.toString() + "?" + ContactsContract.CALLER_IS_SYNCADAPTER + "=true");  
  1109.         op = ContentProviderOperation.newDelete(uri)  
  1110.                 .withSelection(Data.RAW_CONTACT_ID + ">0"null)  
  1111.                 .withYieldAllowed(true)  
  1112.                 .build();   
  1113.         ops.add(op);  
  1114.         //删除RawContacts表的数据  
  1115.         uri = Uri.parse(RawContacts.CONTENT_URI.toString() + "?" + ContactsContract.CALLER_IS_SYNCADAPTER + "=true");  
  1116.         op = ContentProviderOperation.newDelete(RawContacts.CONTENT_URI)  
  1117.                 .withSelection(RawContacts._ID + ">0"null)  
  1118.                 .withYieldAllowed(true)  
  1119.                 .build();  
  1120.         ops.add(op);  
  1121.         //删除Contacts表的数据  
  1122.         uri = Uri.parse(Contacts.CONTENT_URI.toString() + "?" + ContactsContract.CALLER_IS_SYNCADAPTER + "=true");  
  1123.         op = ContentProviderOperation.newDelete(uri)  
  1124.                 .withSelection(Contacts._ID + ">0"null)  
  1125.                 .withYieldAllowed(true)  
  1126.                 .build();  
  1127.         ops.add(op);  
  1128.         //执行批量删除  
  1129.         try {  
  1130.             ContentProviderResult[] results = resolver.applyBatch(ContactsContract.AUTHORITY, ops);  
  1131.             for (ContentProviderResult result : results) {  
  1132.                 num += result.count;  
  1133.                 Log.i(Const.APPTAG, "删除影响的行数:" + result.count);  
  1134.             }  
  1135.             delResult.put("result""1");  
  1136.             delResult.put("obj",  num);  
  1137.         } catch (Exception e) {  
  1138.             Log.i(Const.APPTAG, e.getMessage());  
  1139.             delResult.put("result""-1");  
  1140.             delResult.put("obj""删除失败!" + e.getMessage());  
  1141.         }  
  1142.         if (delResult.size() == 0) {  
  1143.             delResult.put("result""0");  
  1144.             delResult.put("obj""无效删除,联系人信息不正确!");  
  1145.         }  
  1146.         return delResult;  
  1147.     }  
  1148.       
  1149.     /** 
  1150.      * 删除联系人 ,联系人相关联的有三张表,将三张表的数据全部删除 
  1151.      * 部分手机删除第二张即可,部分手机需要删除三张表 
  1152.      * resolver.delete(ContactsContract.Data.CONTENT_URI, null, null); 
  1153.      * resolver.delete(ContactsContract.RawContacts.CONTENT_URI, null, null); 
  1154.      * resolver.delete(ContactsContract.Contacts.CONTENT_URI, null, null); 
  1155.      * @param contactId 
  1156.      * @param groupId 
  1157.      * @return 
  1158.      * 如果删除成功:(1, num); 
  1159.      * 如果删除失败:(-1, "删除失败:" + e.getMessage()); 
  1160.      * 如果信息无效:(0, "无效删除,联系人信息不正确!"); 
  1161.      */  
  1162.     public HashMap<String, Object> delContacts(List<String> contactIds) {  
  1163.         ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>();  
  1164.         ContentProviderOperation op = null;  
  1165.         Uri uri = null;  
  1166.           
  1167.         HashMap<String, Object> delResult = new HashMap<String, Object>();  
  1168.         int num = 0;//删除影响的行数  
  1169.         if (Utils.isEmpty(contactIds)) {  
  1170.             delResult.put("result""0");  
  1171.             delResult.put("obj""无效删除,联系人id不正确!");  
  1172.             return delResult;  
  1173.         }  
  1174.         List<String> ids = new ArrayList<String>();  
  1175.         String selection = " in(";  
  1176.         for (String contactId : contactIds) {  
  1177.             //如果联系人id 不大于 0,或者不存在,循环下一次  
  1178.             if (!Utils.isNumber(contactId) || Long.parseLong(contactId) <= 0 || !isExistContact(contactId)) {  
  1179.                 continue;  
  1180.             }  
  1181.             selection += "?,";  
  1182.             ids.add(contactId);  
  1183.         }  
  1184.         if (ids.size() == 0) {  
  1185.             delResult.put("result""0");  
  1186.             delResult.put("obj""无效联系人id");  
  1187.             return delResult;  
  1188.         }  
  1189.         selection = selection.substring(0, selection.length() - 1) + ")";  
  1190.         String[] selectionArgs = ids.toArray(new String[]{});  
  1191.           
  1192.         //删除Data表的数据  
  1193.         uri = Uri.parse(Data.CONTENT_URI.toString() + "?" + ContactsContract.CALLER_IS_SYNCADAPTER + "=true");  
  1194.         op = ContentProviderOperation.newDelete(uri)  
  1195.                 .withSelection(Data.RAW_CONTACT_ID + selection, selectionArgs)  
  1196.                 .withYieldAllowed(true)  
  1197.                 .build();  
  1198.         ops.add(op);  
  1199.         //删除RawContacts表的数据  
  1200.         uri = Uri.parse(RawContacts.CONTENT_URI.toString() + "?" + ContactsContract.CALLER_IS_SYNCADAPTER + "=true");  
  1201.         op = ContentProviderOperation.newDelete(RawContacts.CONTENT_URI)  
  1202.                 .withSelection(RawContacts._ID + selection, selectionArgs)  
  1203.                 .withYieldAllowed(true)  
  1204.                 .build();  
  1205.         ops.add(op);  
  1206.         //删除Contacts表的数据  
  1207.         uri = Uri.parse(Contacts.CONTENT_URI.toString() + "?" + ContactsContract.CALLER_IS_SYNCADAPTER + "=true");  
  1208.         op = ContentProviderOperation.newDelete(uri)  
  1209.                 .withSelection(Contacts._ID + selection, selectionArgs)  
  1210.                 .withYieldAllowed(true)  
  1211.                 .build();  
  1212.         ops.add(op);  
  1213.           
  1214.         //执行批量删除  
  1215.         try {  
  1216.             ContentProviderResult[] results = resolver.applyBatch(ContactsContract.AUTHORITY, ops);  
  1217.             for (ContentProviderResult result : results) {  
  1218.                 num += result.count;  
  1219.                 Log.i(Const.APPTAG, "删除影响的行数:" + result.count);  
  1220.             }  
  1221.             delResult.put("result""1");  
  1222.             delResult.put("obj",  num);  
  1223.         } catch (Exception e) {  
  1224.             Log.i(Const.APPTAG, e.getMessage());  
  1225.             delResult.put("result""-1");  
  1226.             delResult.put("obj""删除失败!" + e.getMessage());  
  1227.         }  
  1228.         if (delResult.size() == 0) {  
  1229.             delResult.put("result""0");  
  1230.             delResult.put("obj""无效删除,联系人id不正确!");  
  1231.         }  
  1232.         return delResult;  
  1233.     }  
  1234.       
  1235.       
  1236.     /** 
  1237.      *  如果组的id>0: 直接根据组的id删除组内所有联系人; 
  1238.      *  如果参数二为 true :则连组一起删除; 
  1239.      * @param groupId 
  1240.      * @param isDelGroup 
  1241.      * @return 
  1242.      */  
  1243.     public HashMap<String, Object> delContactsByGroup(List<String> groupIds, boolean isDelGroup) {  
  1244.         HashMap<String, Object> result = new HashMap<String, Object>();  
  1245.           
  1246.         if (Utils.isEmpty(groupIds)) {  
  1247.             result.put("result""0");  
  1248.             result.put("obj""无效的组id");  
  1249.             return result;  
  1250.         }  
  1251.         List<String> contactIds = new ArrayList<String>();  
  1252.         List<String> delIds = new ArrayList<String>();  
  1253.         String selection = " in(";  
  1254.         for (String groupId : groupIds) {  
  1255.             //如果联系人id 不大于 0,或者不存在,循环下一次  
  1256.             if (!Utils.isNumber(groupId) || Long.parseLong(groupId) <= 0 || !isExistGroup(groupId)) {  
  1257.                 continue;  
  1258.             }  
  1259.             delIds.add(groupId);  
  1260.             selection += "?,";  
  1261.         }  
  1262.           
  1263.         if (delIds.size() > 0) {  
  1264.             //查询组内的联系人  
  1265.             selection = selection.substring(0, selection.length() - 1) + ")";  
  1266.             String[] selectionArgs = delIds.toArray(new String[]{});  
  1267.               
  1268.             contactIds.addAll(getCotactsByGroup(selection, selectionArgs));  
  1269.             if (contactIds.size() > 0) {  
  1270.                 //删除组内的联系人  
  1271.                 result = delContacts(contactIds);  
  1272.                 Log.i(Const.APPTAG, selection + ";value:" + selectionArgs.length);  
  1273.                 //删除组  
  1274.                 if (result.get("result") != null && isDelGroup) {  
  1275.                     int n = Integer.parseInt(result.get("obj").toString()) + delGroupById(selection, selectionArgs);  
  1276.                     result.put("result""1");  
  1277.                     result.put("obj", n);  
  1278.                 }  
  1279.             }  
  1280.         } else {  
  1281.             result.put("result""-1");  
  1282.             result.put("obj""无效的组id");  
  1283.         }  
  1284.         return result;  
  1285.     }  
  1286.       
  1287.     /** 
  1288.      * 根据多个组的id,查询组内的所有联系人 
  1289.      */  
  1290.     public List<String> getCotactsByGroup(String selection, String[] groupIds) {  
  1291.         List<String> list = new ArrayList<String>();  
  1292.           
  1293.         Cursor groupContactCursor = resolver.query(  
  1294.                         Data.CONTENT_URI,  
  1295.                         new String[] { Data.RAW_CONTACT_ID },  
  1296.                         GroupMembership.GROUP_ROW_ID + selection + " AND "   
  1297.                             + Data.MIMETYPE + "='" + GroupMembership.CONTENT_ITEM_TYPE + "'",  
  1298.                         groupIds, null);  
  1299.   
  1300.         // Second, query the corresponding name of the raw_contact_id  
  1301.         while (groupContactCursor.moveToNext()) {  
  1302.             Cursor contactCursor = resolver.query(  
  1303.                     Data.CONTENT_URI,  
  1304.                     new String[] { Data.RAW_CONTACT_ID},  
  1305.                     Data.MIMETYPE + "=? AND " + Data.RAW_CONTACT_ID + "=?",  
  1306.                     new String[]{ StructuredName.CONTENT_ITEM_TYPE, groupContactCursor.getInt(0) + ""},  
  1307.                     null);  
  1308.             if(contactCursor.moveToFirst()){  
  1309.                 list.add(contactCursor.getString(0));  
  1310.             }  
  1311.             contactCursor.close();  
  1312.         }  
  1313.         groupContactCursor.close();  
  1314.         return list;  
  1315.     }  
  1316.       
  1317.     /** 
  1318.      * 根据id查询联系人是否存在 
  1319.      */  
  1320.     private boolean isExistContact(String id){  
  1321.         if (Utils.isEmpty(id)) {  
  1322.             return false;  
  1323.         }  
  1324.         Cursor cursor = resolver.query(  
  1325.                     Contacts.CONTENT_URI,   
  1326.                     new String[]{ Contacts._ID},   
  1327.                     Contacts._ID + " = ? ",   
  1328.                     new String[]{ id }, null);  
  1329.           
  1330.         if (cursor.moveToFirst()) {  
  1331.             return true;  
  1332.         }  
  1333.         cursor.close();  
  1334.         return false;  
  1335.     }  
  1336.     /** 
  1337.      * 根据组的id查询组是否存在 
  1338.      * @return boolean 
  1339.      */  
  1340.     public boolean isExistGroup(String id) {  
  1341.         if (Utils.isEmpty(id)) {  
  1342.             return false;  
  1343.         }  
  1344.         Cursor cursor = resolver.query(  
  1345.                 Groups.CONTENT_URI,  
  1346.                 new String[] { Groups._ID },   
  1347.                 Groups._ID + "=" + id,   
  1348.                 nullnull);  
  1349.         if(cursor.moveToFirst()) {  
  1350.             return true;  
  1351.         }  
  1352.         cursor.close();  
  1353.         return false;  
  1354.     }  
  1355.       
  1356.     /** 
  1357.      * 批量更新联系人 
  1358.      * @param contacts 
  1359.      * @return  
  1360.      * 如果更新成功:(1, num); 
  1361.      * 如果更新失败:(-1, "更新失败:" + e.getMessage()); 
  1362.      * 如果信息无效:(0, "无效更新,联系人信息不完整!"); 
  1363.      */  
  1364.     public HashMap<String, Object> updateContacts(List<Map<String, Object>> contacts) {  
  1365.         HashMap<String, Object> updateResult = new HashMap<String, Object>();  
  1366.         if (Utils.isEmpty(contacts)) {  
  1367.             updateResult.put("result""0");  
  1368.             updateResult.put("obj""无效更新,联系人信息不完整!");  
  1369.             return updateResult;  
  1370.         }  
  1371.           
  1372.         ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>();  
  1373.         ContentProviderOperation op = null;   
  1374.         int num = 0;//删除影响的行数  
  1375.           
  1376.         for (Map<String, Object> contact : contacts) {  
  1377.               
  1378.             String contactId = (String) contact.get("contactId") ;  
  1379.             //如果,联系人不存在,查看下一个  
  1380.             if (!Utils.isNumber(contactId) || Long.parseLong(contactId) <= 0 || !isExistContact(contactId)) {  
  1381.                 continue;  
  1382.             }  
  1383.             String displayName          = (String) contact.get("displayName");  
  1384.             String familyName           = (String) contact.get("familyName");  
  1385.             String middleName           = (String) contact.get("middleName");  
  1386.             String givenName            = (String) contact.get("givenName");  
  1387.             String prefix               = (String) contact.get("prefix");  
  1388.             String suffix               = (String) contact.get("suffix");  
  1389.             String phoneticName         = (String) contact.get("phoneticName");  
  1390.             String phoneticFamilyName   = (String) contact.get("phoneticFamilyName");  
  1391.             String phoneticMiddleName   = (String) contact.get("phoneticMiddleName");  
  1392.             String phoneticGivenName    = (String) contact.get("phoneticGivenName");  
  1393.             String nickName             = (String) contact.get("nickName");  
  1394.             String birthday             = (String) contact.get("birthday");  
  1395.             String anniversary          = (String) contact.get("anniversary");  
  1396.             String note                 = (String) contact.get("note");  
  1397.             String company              = (String) contact.get("company");  
  1398.             String job                  = (String) contact.get("job");  
  1399.             String department           = (String) contact.get("department");  
  1400.               
  1401.             Map<String, Object> phones    = (Map<String, Object>) contact.get("phones");  
  1402.             Map<String, Object> emails    = (Map<String, Object>) contact.get("emails");  
  1403.             Map<String, Object> address = (Map<String, Object>) contact.get("addresses");  
  1404.             Map<String, Object> ims   = (Map<String, Object>) contact.get("ims");  
  1405.             Map<String, Object> urls  = (Map<String, Object>) contact.get("urls");  
  1406.             Map<String, Object>   groups  = (Map<String, Object>) contact.get("groups");  
  1407.               
  1408.             //如果都为空,循环下一个,联系人信息  
  1409.             if (Utils.isEmpty(displayName) && Utils.isEmpty(address) && Utils.isEmpty(phones)   
  1410.                     && Utils.isEmpty(emails) && Utils.isEmpty(familyName) && Utils.isEmpty(middleName)  
  1411.                     && Utils.isEmpty(givenName) && Utils.isEmpty(prefix) && Utils.isEmpty(suffix)  
  1412.                     && Utils.isEmpty(phoneticName) && Utils.isEmpty(phoneticFamilyName) && Utils.isEmpty(phoneticMiddleName)  
  1413.                     && Utils.isEmpty(phoneticGivenName) && Utils.isEmpty(nickName) && Utils.isEmpty(birthday)  
  1414.                     && Utils.isEmpty(anniversary) && Utils.isEmpty(note) && Utils.isEmpty(company)  
  1415.                     && Utils.isEmpty(job) && Utils.isEmpty(department)) {  
  1416.                 continue;  
  1417.             }  
  1418.               
  1419.             //数据表 uri  
  1420.             Uri uri = Data.CONTENT_URI;  
  1421.             Builder builder = ContentProviderOperation.newUpdate(uri)  
  1422.                         .withSelection(Data.RAW_CONTACT_ID + " =? and " + Data.MIMETYPE + " =?",   
  1423.                                 new String[]{ contactId, StructuredName.CONTENT_ITEM_TYPE })  
  1424.                         .withYieldAllowed(true);  
  1425.               
  1426.             //更新姓名  
  1427.             if (displayName != null) {  
  1428.                 builder.withValue(StructuredName.DISPLAY_NAME, displayName);  
  1429.             }  
  1430.             //更新姓  
  1431.             if (familyName != null) {  
  1432.                 builder.withValue(StructuredName.FAMILY_NAME, familyName);  
  1433.             }  
  1434.             //更新中间名  
  1435.             if (middleName != null) {  
  1436.                 builder.withValue(StructuredName.MIDDLE_NAME, middleName);  
  1437.             }  
  1438.             //更新名  
  1439.             if (givenName != null) {  
  1440.                 builder.withValue(StructuredName.GIVEN_NAME, givenName);  
  1441.             }  
  1442.             //更新前缀  
  1443.             if (prefix != null) {  
  1444.                 builder.withValue(StructuredName.PREFIX, prefix);  
  1445.             }  
  1446.             //更新后缀  
  1447.             if (suffix != null) {  
  1448.                 builder.withValue(StructuredName.SUFFIX, suffix);  
  1449.             }  
  1450.             //更新全拼  
  1451.             if (phoneticName != null) {  
  1452.                 builder.withValue(StructuredName.PHONETIC_NAME, phoneticName);  
  1453.             }  
  1454.             //更新姓拼音  
  1455.             if (phoneticFamilyName != null) {  
  1456.                 builder.withValue(StructuredName.PHONETIC_FAMILY_NAME, phoneticFamilyName);  
  1457.             }  
  1458.             //更新中间名拼音  
  1459.             if (phoneticFamilyName != null) {  
  1460.                 builder.withValue(StructuredName.PHONETIC_MIDDLE_NAME, phoneticMiddleName);  
  1461.             }  
  1462.             //更新名拼音  
  1463.             if (phoneticGivenName != null) {  
  1464.                 builder.withValue(StructuredName.PHONETIC_GIVEN_NAME, phoneticGivenName);  
  1465.             }  
  1466.             ops.add(builder.build());  
  1467.               
  1468.               
  1469.             //更新昵称  
  1470.             if (nickName != null) {  
  1471.                 op = ContentProviderOperation.newUpdate(uri)  
  1472.                         .withSelection(Data.RAW_CONTACT_ID + " =? and " + Data.MIMETYPE + " =?",   
  1473.                                     new String[]{ contactId, Nickname.CONTENT_ITEM_TYPE })  
  1474.                         .withValue(Nickname.NAME, nickName)  
  1475.                         .withYieldAllowed(true)  
  1476.                         .build();  
  1477.                 ops.add(op);  
  1478.             }  
  1479.               
  1480.             //更新生日  
  1481.             if (birthday != null) {  
  1482.                 op = ContentProviderOperation.newUpdate(uri)  
  1483.                         .withSelection(  
  1484.                                         Data.RAW_CONTACT_ID + " =? and " +   
  1485.                                         Data.MIMETYPE       + " =? and " +   
  1486.                                         Event.TYPE          + " =? ",   
  1487.                                     new String[]{   
  1488.                                         contactId,   
  1489.                                         Event.CONTENT_ITEM_TYPE,  
  1490.                                         Event.TYPE_BIRTHDAY + ""})  
  1491.                         .withValue(Event.START_DATE, birthday)  
  1492.                         .withYieldAllowed(true)  
  1493.                         .build();  
  1494.                 ops.add(op);  
  1495.             }  
  1496.               
  1497.             //更新纪念日  
  1498.             if (anniversary != null) {  
  1499.                 op = ContentProviderOperation.newUpdate(uri)  
  1500.                         .withSelection(  
  1501.                                         Data.RAW_CONTACT_ID + " =? and " +   
  1502.                                         Data.MIMETYPE       + " =? and " +   
  1503.                                         Event.TYPE          + " =? ",   
  1504.                                     new String[]{   
  1505.                                         contactId,   
  1506.                                         Event.CONTENT_ITEM_TYPE,  
  1507.                                         Event.TYPE_ANNIVERSARY + ""})  
  1508.                         .withValue(Event.START_DATE, anniversary)  
  1509.                         .withYieldAllowed(true)  
  1510.                         .build();  
  1511.                 ops.add(op);  
  1512.             }  
  1513.             //更新备注  
  1514.             if (note != null) {  
  1515.                 op = ContentProviderOperation.newUpdate(uri)  
  1516.                         .withSelection(Data.RAW_CONTACT_ID + " =? and " + Data.MIMETYPE + " =?",   
  1517.                                     new String[]{ contactId, Note.CONTENT_ITEM_TYPE})  
  1518.                         .withValue(Note.NOTE, note)  
  1519.                         .withYieldAllowed(true)  
  1520.                         .build();  
  1521.                 ops.add(op);  
  1522.             }  
  1523.             //更新组织,公司  
  1524.             if (company != null || job != null || department != null) {  
  1525.                 Builder tempBuilder = ContentProviderOperation.newUpdate(uri)  
  1526.                 .withSelection(  
  1527.                         Data.RAW_CONTACT_ID + " =? and " +   
  1528.                         Data.MIMETYPE       + " =? and " +   
  1529.                         Organization.TYPE   + " =? ",   
  1530.                         new String[]{   
  1531.                                 contactId,   
  1532.                                 Organization.CONTENT_ITEM_TYPE,  
  1533.                                 Organization.TYPE_WORK + ""})  
  1534.                                 .withYieldAllowed(true);  
  1535.                 if (company != null) {  
  1536.                     tempBuilder.withValue(Organization.COMPANY, company);  
  1537.                 }  
  1538.                 if (job != null) {  
  1539.                     tempBuilder.withValue(Organization.TITLE, job);  
  1540.                 }  
  1541.                 if (department != null) {  
  1542.                     tempBuilder.withValue(Organization.DEPARTMENT, department);  
  1543.                 }  
  1544.                 ops.add(tempBuilder.build());  
  1545.             }  
  1546.             //更新电话号码  
  1547.             if (!Utils.isEmpty(phones)) {  
  1548.                 for (String key : phones.keySet()) {  
  1549.                     if (Utils.isEmpty(key)) {//不能为空  
  1550.                         continue;  
  1551.                     }  
  1552.                     String[] temp = key.split("_");  
  1553.                     if (!Utils.isNumber(temp[1])) {  
  1554.                         continue;  
  1555.                     }  
  1556.                     Long dataId = Long.parseLong(temp[1]);  
  1557. //                  String phoneType = temp[1];//电话的类型,不需要,因为dataid是唯一的所以根据id修改数据就行了  
  1558.                       
  1559.                     String where = Data._ID + " =?";   
  1560. //                     + " and " + Data.RAW_CONTACT_ID + " =? and " + Data.MIMETYPE + " =?";  
  1561.           
  1562.                     String[] val = new String[] {String.valueOf(dataId),};  
  1563.                     //String.valueOf(contactId), Phone.CONTENT_ITEM_TYPE  
  1564.                       
  1565.                     //如果电话号码为空,就删除这个电话号码,如果不为空,更新  
  1566.                     if (Utils.isEmpty(phones.get(key))) {  
  1567.                         op = ContentProviderOperation.newDelete(uri)  
  1568.                                 .withSelection(where, val)  
  1569.                                 .withYieldAllowed(true)  
  1570.                                 .build();  
  1571.                         ops.add(op);  
  1572.                     } else {  
  1573.                         op = ContentProviderOperation.newUpdate(uri)  
  1574.                                 .withSelection(where,  val)  
  1575.                                 .withValue(Phone.NUMBER, phones.get(key).toString())  
  1576.                                 .withYieldAllowed(true)  
  1577.                                 .build();  
  1578.                         ops.add(op);  
  1579.                     }  
  1580.                 }  
  1581.             }  
  1582.             //更新电子邮件  
  1583.             if (!Utils.isEmpty(emails)) {  
  1584.                 for (String key : emails.keySet()) {  
  1585.                     if (Utils.isEmpty(key)) {//不能为空  
  1586.                         continue;  
  1587.                     }  
  1588.                     String[] temp = key.split("_");  
  1589.                     if (!Utils.isNumber(temp[1])) {  
  1590.                         continue;  
  1591.                     }  
  1592.                     Long dataId = Long.parseLong(temp[1]);  
  1593. //                  String phoneType = temp[1];//Email的类型,不需要,因为dataid是唯一的所以根据id修改数据就行了  
  1594.                       
  1595.                     String where = Data._ID + " =?";   
  1596.           
  1597.                     String[] val = new String[] {String.valueOf(dataId),};  
  1598.                       
  1599.                     //如果Email为空,就删除这个Email,如果不为空,更新  
  1600.                     if (Utils.isEmpty(emails.get(key))) {  
  1601.                         op = ContentProviderOperation.newDelete(uri)  
  1602.                                 .withSelection(where, val)  
  1603.                                 .withYieldAllowed(true)  
  1604.                                 .build();  
  1605.                         ops.add(op);  
  1606.                     } else {  
  1607.                         op = ContentProviderOperation.newUpdate(uri)  
  1608.                                 .withSelection(where,  val)  
  1609.                                 .withValue(Email.DATA, emails.get(key).toString())  
  1610.                                 .withYieldAllowed(true)  
  1611.                                 .build();  
  1612.                         ops.add(op);  
  1613.                     }  
  1614.                 }  
  1615.             }  
  1616.             //更新地址  
  1617.             if (!Utils.isEmpty(address)) {  
  1618.                 for (String key : address.keySet()) {  
  1619.                     if (Utils.isEmpty(key)) {//不能为空  
  1620.                         continue;  
  1621.                     }  
  1622.                     String[] temp = key.split("_");  
  1623.                     if (!Utils.isNumber(temp[1])) {  
  1624.                         continue;  
  1625.                     }  
  1626.                     Long dataId = Long.parseLong(temp[1]);  
  1627. //                  String phoneType = temp[1];//地址的类型,不需要,因为dataid是唯一的所以根据id修改数据就行了  
  1628.                       
  1629.                     String where = Data._ID + " =?";   
  1630.           
  1631.                     String[] val = new String[] {String.valueOf(dataId),};  
  1632.                       
  1633.                     //如果地址为空,就删除这个地址,如果不为空,更新  
  1634.                     if (Utils.isEmpty(address.get(key))) {  
  1635.                         op = ContentProviderOperation.newDelete(uri)  
  1636.                                 .withSelection(where, val)  
  1637.                                 .withYieldAllowed(true)  
  1638.                                 .build();  
  1639.                         ops.add(op);  
  1640.                     } else {  
  1641.                         op = ContentProviderOperation.newUpdate(uri)  
  1642.                                 .withSelection(where,  val)  
  1643.                                 .withValue(StructuredPostal.FORMATTED_ADDRESS, address.get(key).toString())  
  1644.                                 .withYieldAllowed(true)  
  1645.                                 .build();  
  1646.                         ops.add(op);  
  1647.                     }  
  1648.                 }  
  1649.             }  
  1650.               
  1651.             //更新im  
  1652.             if (!Utils.isEmpty(ims)) {  
  1653.                 for (String key : ims.keySet()) {  
  1654.                     if (Utils.isEmpty(key)) {//不能为空  
  1655.                         continue;  
  1656.                     }  
  1657.                     String[] temp = key.split("_");  
  1658.                     if (!Utils.isNumber(temp[1])) {  
  1659.                         continue;  
  1660.                     }  
  1661.                     Long dataId = Long.parseLong(temp[1]);  
  1662.                       
  1663.                     String where = Data._ID + " =?";   
  1664.           
  1665.                     String[] val = new String[] {String.valueOf(dataId),};  
  1666.                       
  1667.                     //如果im为空,就删除这个im,如果不为空,更新  
  1668.                     if (Utils.isEmpty(ims.get(key))) {  
  1669.                         op = ContentProviderOperation.newDelete(uri)  
  1670.                                 .withSelection(where, val)  
  1671.                                 .withYieldAllowed(true)  
  1672.                                 .build();  
  1673.                         ops.add(op);  
  1674.                     } else {  
  1675.                         op = ContentProviderOperation.newUpdate(uri)  
  1676.                                 .withSelection(where,  val)  
  1677.                                 .withValue(Im.DATA, ims.get(key).toString())  
  1678.                                 .withYieldAllowed(true)  
  1679.                                 .build();  
  1680.                         ops.add(op);  
  1681.                     }  
  1682.                 }  
  1683.             }  
  1684.             //更新 urls  
  1685.             if (!Utils.isEmpty(urls)) {  
  1686.                 for (String key : urls.keySet()) {  
  1687.                     if (Utils.isEmpty(key)) {//不能为空  
  1688.                         continue;  
  1689.                     }  
  1690.                     String[] temp = key.split("_");  
  1691.                     if (!Utils.isNumber(temp[1])) {  
  1692.                         continue;  
  1693.                     }  
  1694.                     Long dataId = Long.parseLong(temp[1]);  
  1695.                       
  1696.                     String where = Data._ID + " =?";   
  1697.           
  1698.                     String[] val = new String[] {String.valueOf(dataId),};  
  1699.                       
  1700.                     //如果im为空,就删除这个im,如果不为空,更新  
  1701.                     if (Utils.isEmpty(urls.get(key))) {  
  1702.                         op = ContentProviderOperation.newDelete(uri)  
  1703.                                 .withSelection(where, val)  
  1704.                                 .withYieldAllowed(true)  
  1705.                                 .build();  
  1706.                         ops.add(op);  
  1707.                     } else {  
  1708.                         op = ContentProviderOperation.newUpdate(uri)  
  1709.                                 .withSelection(where,  val)  
  1710.                                 .withValue(Website.URL, urls.get(key).toString())  
  1711.                                 .withYieldAllowed(true)  
  1712.                                 .build();  
  1713.                         ops.add(op);  
  1714.                     }  
  1715.                 }  
  1716.             }  
  1717.             //更新组  
  1718.             if (!Utils.isEmpty(groups)) {  
  1719.                 for (String key : groups.keySet()) {  
  1720.                     if (Utils.isEmpty(key)) {//不能为空  
  1721.                         continue;  
  1722.                     }  
  1723.                     //1:title  
  1724.                     String[] temp = key.split("_");  
  1725.                     if (!Utils.isNumber(temp[2]) && !isExistGroup(temp[2])) {  
  1726.                         continue;  
  1727.                     }  
  1728.                     Long dataId = Long.parseLong(temp[1]);  
  1729.                     Long groupId = Long.parseLong(temp[2]);  
  1730.                       
  1731.                     String where = Data._ID + " =?";   
  1732.                       
  1733.                     String[] val = new String[] {String.valueOf(dataId),};  
  1734.                     //如果组的title为空,就删除和这个组的关系,如果不为空,更新  
  1735.                     if (Utils.isEmpty(groups.get(key))) {  
  1736.                         op = ContentProviderOperation.newDelete(uri)  
  1737.                                 .withSelection(where, val)  
  1738.                                 .withYieldAllowed(true)  
  1739.                                 .build();  
  1740.                         ops.add(op);  
  1741.                     } else {  
  1742.                         op = ContentProviderOperation.newUpdate(uri)  
  1743.                                 .withSelection(where,  val)  
  1744.                                 .withValue(GroupMembership.GROUP_ROW_ID, groupId)  
  1745.                                 .withYieldAllowed(true)  
  1746.                                 .build();  
  1747.                         ops.add(op);  
  1748.                     }  
  1749.                 }  
  1750.             }  
  1751.             try {  
  1752.                 ContentProviderResult[] results = resolver.applyBatch(ContactsContract.AUTHORITY, ops);  
  1753.                 for (ContentProviderResult result : results) {  
  1754.                     num += result.count;  
  1755.                     Log.i(Const.APPTAG, "更新影响的行数:" + result.count);  
  1756.                 }  
  1757.                 updateResult.put("result""1");  
  1758.                 updateResult.put("obj", num);  
  1759.             } catch (Exception e) {  
  1760.                 Log.i(Const.APPTAG, e.getMessage());  
  1761.                 updateResult.put("result""-1");  
  1762.                 updateResult.put("obj",  "更新失败:" + e.getMessage());  
  1763.             }  
  1764.         }  
  1765.         if (updateResult.size() == 0) {  
  1766.             updateResult.put("result""0");  
  1767.             updateResult.put("obj""执行了更新,但是没有受影响的数据,请检查数据是否有效!");  
  1768.         }  
  1769.         return updateResult;  
  1770.     }  
  1771.       
  1772.     /** 
  1773.      * 给联系人添加一个或多个电话号码 
  1774.      * @param phones 
  1775.      * @return 
  1776.      */  
  1777.     public HashMap<String, Object> addPhoneByContactId(Map<String, String> phones) {  
  1778.         HashMap<String, Object> addResult = new HashMap<String, Object>();  
  1779.         if (Utils.isEmpty(phones)) {  
  1780.             addResult.put("result""0");  
  1781.             addResult.put("obj""无效插入,电话为空!");  
  1782.             return addResult;  
  1783.         }  
  1784.           
  1785.         Uri uri = Data.CONTENT_URI;  
  1786.         //插入电话号码  
  1787.         String id = phones.get("contactId");  
  1788.         String phone = phones.get("phone");  
  1789.         String type = phones.get("type");  
  1790.         //联系人id和电话都不能为空  
  1791.         if (Utils.isNumber(id) && !Utils.isEmpty(phone)) {  
  1792.             ContentValues values = new ContentValues();  
  1793.             values.put(Data.RAW_CONTACT_ID, id);  
  1794.             values.put(Data.MIMETYPE, Phone.CONTENT_ITEM_TYPE);  
  1795.             values.put(Phone.NUMBER, phone);  
  1796.             values.put(Phone.LABEL, "手机号");  
  1797.               
  1798.             if(type.equalsIgnoreCase("mobile")) {//如果是手机号码  
  1799.                 values.put(Phone.TYPE, Phone.TYPE_MOBILE);  
  1800.             } else if(type.equalsIgnoreCase("work")) {//如果是公司电话  
  1801.                 values.put(Phone.TYPE, Phone.TYPE_WORK);  
  1802.             } else if(type.equalsIgnoreCase("faxWork")) {//如果是公司传真号码  
  1803.                 values.put(Phone.TYPE, Phone.TYPE_FAX_WORK);  
  1804.             } else if(type.equalsIgnoreCase("home")) {//如果是家庭电话  
  1805.                 values.put(Phone.TYPE, Phone.TYPE_HOME);  
  1806.             } else {//其他  
  1807.                 values.put(Phone.TYPE, Phone.TYPE_OTHER);  
  1808.             }  
  1809.             Uri u = resolver.insert(uri, values);  
  1810.               
  1811.             addResult.put("result""1");  
  1812.             addResult.put("obj", u.toString());  
  1813.         } else {  
  1814.             addResult.put("result""0");  
  1815.             addResult.put("obj""无效插入,联系人id和电话为空!");  
  1816.         }  
  1817.           
  1818.         return addResult;  
  1819.     }  
  1820. //  /**  
  1821. //   * 删除和组的所有关系  
  1822. //   */  
  1823. //  private void test(){  
  1824.         //不管分组的数据是否为空,都先删除联系人和组的所有关系,然后再添加,新的关系  
  1825. //      String where = GroupMembership.RAW_CONTACT_ID + "=? and " +  
  1826. //              GroupMembership.MIMETYPE + "=?";  
  1827. //      String[] val = { contactId, GroupMembership.CONTENT_ITEM_TYPE};  
  1828. //        
  1829. //      op = ContentProviderOperation.newDelete(uri)  
  1830. //              .withSelection(where, val)  
  1831. //              .withYieldAllowed(true)  
  1832. //              .build();  
  1833. //      ops.add(op);  
  1834. //  }  
  1835. }  
转:http://blog.csdn.net/fk_null/article/details/16826345。
0 0