Android本地通訊錄

文章轉自http://my.oschina.net/xiahuawuyu/blog/87953


package
com.cy.contact.dao;
 
import java.util.ArrayList;
import java.util.List;
 
import android.content.ContentProviderOperation;
import android.content.ContentProviderResult;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.content.OperationApplicationException;
import android.database.Cursor;
import android.net.Uri;
import android.os.RemoteException;
import android.provider.ContactsContract;
import android.provider.ContactsContract.Data;
import android.provider.ContactsContract.RawContacts;
import android.provider.ContactsContract.CommonDataKinds.Email;
import android.provider.ContactsContract.CommonDataKinds.Im;
import android.provider.ContactsContract.CommonDataKinds.Nickname;
import android.provider.ContactsContract.CommonDataKinds.Note;
import android.provider.ContactsContract.CommonDataKinds.Organization;
import android.provider.ContactsContract.CommonDataKinds.Phone;
import android.provider.ContactsContract.CommonDataKinds.StructuredName;
import android.provider.ContactsContract.CommonDataKinds.StructuredPostal;
import android.provider.ContactsContract.CommonDataKinds.Website;
 
import com.cy.contact.activity.R;
import com.cy.contact.pojo.ContentIndex;
import com.cy.contact.pojo.Group;
import com.cy.contact.pojo.User;
import com.cy.contact.pojo.UserContent;
import com.cy.contact.pojo.UserIndex;
import com.cy.contact.usercontent.action.ActionCode;
import com.cy.contact.util.HypyUtil;
import com.cy.contact.util.Constant.AuthSystem;
import com.cy.contact.util.Constant.SourceCategory;
import com.j256.ormlite.dao.Dao;
import com.j256.ormlite.dao.ForeignCollection;
 
/**
 * 本地通訊錄增刪改查類
 *
 * @author wangqiang
 *
 */
public class NativeContactImpl {
    private Context context;
 
    public NativeContactImpl(Context context) {
        this.context = context;
    }
    private UserDao udao;
    private Dao dao;
    DaoFactory daoFactory;
     
 
    /**
     * 添加數據到通訊錄中
     */
    public void addContact(User user) {
        ContentValues values = new ContentValues();
        UserIndex index=null;
        String source=SourceCategory.SourceSystem.value;
         
        ForeignCollection<UserIndex> listIndex=user.getListIndex();
        for(UserIndex i:listIndex){
            if(SourceCategory.SourceSystem.value.equals(i.getSourceCategory())){
                index=i;
            }
        }
         
        long rawContactId =0;
         
        if(index!=null){
            rawContactId=Long.parseLong(index.getSourceUserId());
        }else{
            // 首先向RawContacts.CONTENT_URI執行一個空值插入,目的是獲取系統返回的rawContactId
            Uri rawContactUri = context.getContentResolver().insert(
                    RawContacts.CONTENT_URI, values);
            rawContactId = ContentUris.parseId(rawContactUri);
            index=new UserIndex();    //設置來源索引信息
        }
         
        // 往data表入姓名數據
        values.clear();
        //姓名分開添加時候使用
        /*
        values.put(Data.RAW_CONTACT_ID, rawContactId);
        values.put(Data.MIMETYPE, StructuredName.CONTENT_ITEM_TYPE);
        values.put(StructuredName.FAMILY_NAME, user.getXing());
        values.put(StructuredName.GIVEN_NAME, user.getMing());
        context.getContentResolver().insert(
                android.provider.ContactsContract.Data.CONTENT_URI, values);
        */
        // 往data表入姓名數據
        values.put(Data.RAW_CONTACT_ID, rawContactId);
        values.put(Data.MIMETYPE, StructuredName.CONTENT_ITEM_TYPE);
        values.put(StructuredName.DISPLAY_NAME, user.getMemberName());
        context.getContentResolver().insert(android.provider.ContactsContract.Data.CONTENT_URI, values);
         
        user.getUpdateIndex().add(index);     
        index.setSourceUserId(rawContactId+"");
        index.setSourceCategory(source);
         
        List<UserContent> list = user.getListContent();
        for(int i = 0 ; i <list.size(); i++){
            UserContent content=list.get(i);
            System.out.println("mark:"+content.getContentMark()+"   text:"+content.getContentText());
            String authSystemFlag=content.getSystemSynch();
            //修改或者刪除原來授權的信息
            ContentIndex contentIndex=null;
            List<ContentIndex> listcIndex=(List<ContentIndex>) content.getListIndex();
            if(listcIndex!=null){
                 
                for(ContentIndex ci:listcIndex){
                    if(SourceCategory.SourceSystem.value.equals(ci.getSourceCategory())){
                        contentIndex=ci;
                    }
                }
            }
            System.out.println("contentIndex:"+contentIndex);
            if(AuthSystem.Forbidden.value.equals(authSystemFlag)){  //沒有授權,或者取消授權,跳出本次循環
                 
                if(contentIndex!=null){     //執行修改或者刪除工作
                    String sourceDataId=contentIndex.getSourceId();
                    System.out.println("sourceDataId:"+sourceDataId);
                    //刪除操作
                    if(sourceDataId!=null){
                        System.out.println("刪除聯繫人屬性");
                        deleteProperty(sourceDataId);
                    }
                    continue;
                }
                continue;
            }
             
            if(contentIndex!=null){     //執行修改
                String contactId=index.getSourceUserId();
                String sourceDataId=contentIndex.getSourceId();
                 
                //修改操作
                System.out.println("修改");
                continue;
            }
             
             
             
            String cateFlag = content.getContentCategory();
            //添加電話號碼
            if(cateFlag == ActionCode.PHONE_ACTION){
                Uri uri=addPhone(rawContactId,content.getContentText());
                //和警務通訊錄db的   索引關係
                setUserContentIndex(content,uri,source);
            }
             
            //添加email數據
            if(cateFlag == ActionCode.EMAIL_ACTION){
                Uri uri=addEmail(rawContactId,content.getContentText());
                setUserContentIndex(content,uri,source);
            }
            //添加 地址
            if(cateFlag == ActionCode.ADDRESS_ACTION){
                Uri uri=addAddress(rawContactId,content.getContentText());
                setUserContentIndex(content,uri,source);
            }
             
            //添加組織包括公司等信息
            if(cateFlag == ActionCode.ORIGNIZE_ACTION){
                Uri uri=addOrganization(rawContactId,content.getContentText());
                setUserContentIndex(content,uri,source);
            }
            //添加IM
            if(cateFlag == ActionCode.IM_ACTION){
                Uri uri=addIM(rawContactId,content.getContentText());
                setUserContentIndex(content,uri,source);
            }
            //添加備註
            if(cateFlag == ActionCode.REMARK_ACTION){
                Uri uri=addRemark(rawContactId,content.getContentText());
                setUserContentIndex(content,uri,source);
            }
            //添加暱稱
            if(cateFlag == ActionCode.NICK_ACTION){
                Uri uri=addNickName(rawContactId, content.getContentText());
                setUserContentIndex(content,uri,source);
            }
            //添加網站
            if(cateFlag == ActionCode.HYPERLINK_ACTION){
                Uri uri=addWebSite(rawContactId,content.getContentText());
                setUserContentIndex(content,uri,source);
            }
            /*
            //添加互聯網通話
            if(cateFlag == ActionCode.WEB_PHONE){
                values.clear();
                values.put(Data.RAW_CONTACT_ID, rawContactId);
                values.put(Data.MIMETYPE, Intents.)
                values.put(key, value)
                values.put(key, value);
            }
            */
             
             
        }
         
         
         
    }
     
    /**
     * 添加電話號碼
     * @param rawContactId  聯繫人ID
     * @param content       電話號碼
     * @return
     */
    public Uri addPhone(long rawContactId,String content){
        ContentValues values=new ContentValues();
        values.put(
                android.provider.ContactsContract.Contacts.Data.RAW_CONTACT_ID,
                rawContactId);
        values.put(Data.MIMETYPE, Phone.CONTENT_ITEM_TYPE);
        values.put(Phone.NUMBER, content);
        values.put(Phone.TYPE, Phone.TYPE_MOBILE);
        Uri uri=context.getContentResolver().insert(
                android.provider.ContactsContract.Data.CONTENT_URI, values);
        return uri;
    }
     
     
    /**
     * 添加email
     * @param rawContactId
     * @param content
     * @return
     */
    public Uri addEmail(long rawContactId,String content){
        ContentValues values=new ContentValues();
        values.put(Data.RAW_CONTACT_ID, rawContactId);
        values.put(Data.MIMETYPE, Email.CONTENT_ITEM_TYPE);
        values.put(Email.DATA, content);
        values.put(Email.TYPE, Email.TYPE_WORK);
        Uri uri=context.getContentResolver().insert(android.provider.ContactsContract.Data.CONTENT_URI, values);
        return uri;
    }
     
    /**
     * 添加通訊地址
     * @param rawContactId
     * @param content
     * @return
     */
    public Uri addAddress(long rawContactId,String content){
        ContentValues values=new ContentValues();
        values.put(Data.RAW_CONTACT_ID, rawContactId);
        values.put(Data.MIMETYPE,StructuredPostal.CONTENT_ITEM_TYPE );
        values.put(StructuredPostal.DATA, content);
        values.put(StructuredPostal.TYPE, StructuredPostal.TYPE_WORK);
        Uri uri=context.getContentResolver().insert(android.provider.ContactsContract.Data.CONTENT_URI, values);
        return uri;
    }
     
    /**
     * 添加組織
     * @param rawContactId
     * @param content
     * @return
     */
    public Uri addOrganization(long rawContactId,String content){
        ContentValues values=new ContentValues();
        values.put(Data.RAW_CONTACT_ID, rawContactId);
        values.put(Data.MIMETYPE, Organization.CONTENT_ITEM_TYPE);
        values.put(Organization.DATA, content);
        values.put(Organization.TYPE, Organization.TYPE_WORK);
 
        Uri uri=context.getContentResolver().insert(android.provider.ContactsContract.Data.CONTENT_URI, values);
        return uri;
    }
     
    /**
     * 添加即時通訊號碼  qq等
     * @param rawContactId
     * @param content
     * @return
     */
    public Uri  addIM(long rawContactId,String content){
        ContentValues values=new ContentValues();
        values.put(Data.RAW_CONTACT_ID, rawContactId);
        values.put(Data.MIMETYPE, Im.CONTENT_ITEM_TYPE);
        values.put(Im.DATA,content);
        values.put(Im.TYPE, Im.TYPE_WORK);
        Uri uri=context.getContentResolver().insert(android.provider.ContactsContract.Data.CONTENT_URI, values);
        return uri;
    }
     
    /**
     * 添加備註
     * @param rawContactId
     * @param content
     * @return
     */
    public Uri addRemark(long rawContactId,String content){
        ContentValues values=new ContentValues();
        values.put(Data.RAW_CONTACT_ID, rawContactId);
        values.put(Data.MIMETYPE, Note.CONTENT_ITEM_TYPE);
        values.put(Note.DATA1,content);
        Uri uri=context.getContentResolver().insert(android.provider.ContactsContract.Data.CONTENT_URI, values);
        return uri;
    }
     
    /**
     * 添加暱稱
     * @param rawContactId
     * @param content
     * @return
     */
    public Uri addNickName(long rawContactId,String content){
        ContentValues values=new ContentValues();
        values.put(Data.RAW_CONTACT_ID, rawContactId);
        values.put(Data.MIMETYPE, Nickname.CONTENT_ITEM_TYPE);
        values.put(Nickname.DATA, content);
        values.put(Nickname.TYPE, Nickname.TYPE_CUSTOM);
        Uri uri=context.getContentResolver().insert(android.provider.ContactsContract.Data.CONTENT_URI, values);
        return uri;
    }
     
    /**
     * 添加網址
     * @param rawContactId
     * @param content
     * @return
     */
    public Uri addWebSite(long rawContactId,String content){
        ContentValues values=new ContentValues();
        values.put(Data.RAW_CONTACT_ID, rawContactId);
        values.put(Data.MIMETYPE, Website.CONTENT_ITEM_TYPE);
        values.put(Website.DATA, content);
        values.put(Website.TYPE, Website.TYPE_WORK);
        Uri uri=context.getContentResolver().insert(android.provider.ContactsContract.Data.CONTENT_URI, values);
        return uri;
    }
     
    /**
     * 查詢系統分組
     *
     * @return
     */
    public List<Group> getGroups() {
        List<Group> listGroup = new ArrayList<Group>();
        Cursor groupCursor = context.getContentResolver().query(
                ContactsContract.Groups.CONTENT_URI,
                new String[] { ContactsContract.Groups._ID,
                        ContactsContract.Groups.TITLE }, null, null, null);
        while (groupCursor.moveToNext()) {
            String groupId = groupCursor.getString(0);
            String groupTitle = groupCursor.getString(1);
            Group group = new Group();
            group.setSystemGroupId(groupId);
            group.setGroupName(groupTitle);
            listGroup.add(group);
             
        }
        return listGroup;
    }
 
     
    /**
     * 獲取聯繫人
     *
     * @return
     */
    public List<User>  getUsers(){
        List<User> listUser = new ArrayList<User>();
         
        String source=SourceCategory.SourceSystem.value;
        ContentResolver resolver = context.getContentResolver();
        // 獲得所有的聯繫人 
        Cursor cur = resolver.query( 
                ContactsContract.Contacts.CONTENT_URI, 
                null
                null
                null
                ContactsContract.Contacts.DISPLAY_NAME 
                        + " COLLATE LOCALIZED ASC"); 
        // 循環遍歷 
        if (cur.moveToFirst()) { 
            int idColumn = cur.getColumnIndex(ContactsContract.Contacts._ID); 
    
            int displayNameColumn = cur 
                    .getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME); 
             
            do
                List<UserContent>  listContents=new ArrayList<UserContent>();
                User user=new User();   
                UserIndex index=new UserIndex();
                user.getUpdateIndex().add(index);         //設置來源索引信息
                // 獲得聯繫人的ID號 
                String contactId = cur.getString(idColumn); 
                 
                index.setSourceUserId(contactId);
                index.setSourceCategory(source);
               // index.setUser(user);
                 
                // 獲得聯繫人姓名 
                String disPlayName = cur.getString(displayNameColumn); 
                user.setMemberName(disPlayName);
                user.setFirstLetter(HypyUtil.cn2py(disPlayName));
                 
                // 查看該聯繫人有多少個電話號碼。如果沒有這返回值爲0 
                int phoneCount = cur 
                        .getInt(cur 
                                .getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER)); 
                if (phoneCount > 0) { 
                    // 獲得聯繫人的電話號碼 
                    Cursor phones = resolver.query( 
                            ContactsContract.CommonDataKinds.Phone.CONTENT_URI, 
                            null
                            ContactsContract.CommonDataKinds.Phone.CONTACT_ID 
                                    + " = " + contactId, null, null); 
                    if (phones.moveToFirst()) { 
                        do
                             
                            // 遍歷所有的電話號碼 
                            int id = phones.getInt(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone._ID));
                            String phoneNumber = phones 
                                    .getString(phones 
                                            .getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER)); 
                            int phoneType = phones 
                                    .getInt(phones 
                                            .getColumnIndex(ContactsContract.CommonDataKinds.Phone.TYPE));
                            String label=context.getString(Phone.getTypeLabelResource(phoneType));
                            
                             
                            UserContent content=new UserContent();
                            content.setContentMark(label);
                            content.setContentText(phoneNumber);
                            content.setContentCategory(ActionCode.PHONE_ACTION);
                             
                            setUserContentIndex(content,id+"",SourceCategory.SourceSystem.value);
                            listContents.add(content);
                        } while (phones.moveToNext()); 
                    
                
   
                // 獲取該聯繫人郵箱 
                Cursor emails = resolver.query( 
                        ContactsContract.CommonDataKinds.Email.CONTENT_URI, 
                        null
                        ContactsContract.CommonDataKinds.Phone.CONTACT_ID 
                                + " = " + contactId, null, null); 
                if (emails.moveToFirst()) { 
                    do
                          
                        // 遍歷所有的郵箱 
                        int id = emails.getInt(emails.getColumnIndex(ContactsContract.CommonDataKinds.Email._ID));
                        int emailType = emails 
                                .getInt(emails 
                                        .getColumnIndex(ContactsContract.CommonDataKinds.Email.TYPE)); 
                        String emailValue = emails 
                                .getString(emails 
                                        .getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA)); 
                        String label=context.getString(Email.getTypeLabelResource(emailType));
 
                         
                        UserContent content=new UserContent();
                        content.setContentMark(label);
                        content.setContentText(emailValue);
                        content.setContentCategory(ActionCode.EMAIL_ACTION);
                         
                        setUserContentIndex(content,id+"",SourceCategory.SourceSystem.value);
                        listContents.add(content);
                         
                    } while (emails.moveToNext()); 
                
   
                // 獲取該聯繫人IM 
                Cursor IMs = resolver.query( 
                        Data.CONTENT_URI, 
                        new String[] { Im._ID, Im.PROTOCOL, Im.DATA ,Im.TYPE}, 
                        Data.CONTACT_ID + "=?" + " AND " + Data.MIMETYPE + "='" 
                                + Im.CONTENT_ITEM_TYPE + "'"
                        new String[] { contactId }, null); 
                if (IMs.moveToFirst()) { 
                    do
                         
                        int id = IMs.getInt(IMs.getColumnIndex(ContactsContract.CommonDataKinds.Im._ID));
                        int type=IMs.getInt(IMs.getColumnIndex(Im.TYPE));
                        String protocol = IMs.getString(IMs 
                                .getColumnIndex(Im.PROTOCOL)); 
                        String data = IMs 
                                .getString(IMs.getColumnIndex(Im.DATA)); 
                        String label=context.getString(Im.getTypeLabelResource(type));
                         
                         
                        UserContent content=new UserContent();
                        content.setContentMark(label);
                        content.setContentText(data);
                        content.setContentCategory(ActionCode.NORMAL_ACTION);
                         
                        setUserContentIndex(content,id+"",SourceCategory.SourceSystem.value);
                        listContents.add(content);
                    } while (IMs.moveToNext()); 
                
   
                // 獲取該聯繫人地址 
                Cursor address =resolver 
                        .query( 
                                ContactsContract.CommonDataKinds.StructuredPostal.CONTENT_URI, 
                                null
                                ContactsContract.CommonDataKinds.Phone.CONTACT_ID 
                                        + " = " + contactId, null, null); 
                if (address.moveToFirst()) { 
                    do
                         
                        int id = address.getInt(address.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal._ID));
                        int type=address.getInt(address.getColumnIndex(StructuredPostal.TYPE));
                        // 遍歷所有的地址 
                        String street = address 
                                .getString(address 
                                        .getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.STREET)); 
                        String city = address 
                                .getString(address 
                                        .getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.CITY)); 
                        String region = address 
                                .getString(address 
                                        .getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.REGION)); 
                        String postCode = address 
                                .getString(address 
                                        .getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.POSTCODE)); 
                        String formatAddress = address 
                                .getString(address 
                                        .getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.FORMATTED_ADDRESS)); 
                     
                     
                    String label=context.getString(StructuredPostal.getTypeLabelResource(type));
                     
                    UserContent content=new UserContent();
                    content.setContentMark(label);
                    content.setContentText(formatAddress);
                    content.setContentCategory(ActionCode.NORMAL_ACTION);
                     
                    setUserContentIndex(content,id+"",SourceCategory.SourceSystem.value);
                    listContents.add(content);
                    } while (address.moveToNext()); 
                
   
                // 獲取該聯繫人公司
                Cursor organizations = resolver.query( 
                        Data.CONTENT_URI, 
                        new String[] { Organization._ID, Organization.TYPE,Organization.COMPANY, 
                                Organization.TITLE }, 
                        Data.CONTACT_ID + "=?" + " AND " + Data.MIMETYPE + "='" 
                                + Organization.CONTENT_ITEM_TYPE + "'"
                        new String[] { contactId }, null); 
                if (organizations.moveToFirst()) { 
                    do
                        int id = organizations.getInt(organizations.getColumnIndex(ContactsContract.CommonDataKinds.Organization._ID));
                        int type=organizations.getInt(organizations.getColumnIndex(Organization.TYPE));
                        String company = organizations.getString(organizations 
                                .getColumnIndex(Organization.COMPANY)); 
                        String title = organizations.getString(organizations 
                                .getColumnIndex(Organization.TITLE)); 
                         
                        UserContent content=new UserContent();
                        content.setContentMark(context.getString(Organization.getTypeLabelResource(type)));
                        content.setContentText(company+":"+title);
                        content.setContentCategory(ActionCode.NORMAL_ACTION);
                         
                         
                        setUserContentIndex(content,id+"",SourceCategory.SourceSystem.value);
                        listContents.add(content);
                         
                    } while (organizations.moveToNext()); 
                
   
                // 獲取備註信息 
                Cursor notes = resolver.query( 
                        Data.CONTENT_URI, 
                        new String[] { Note._ID,Note.NOTE}, 
                        Data.CONTACT_ID + "=?" + " AND " + Data.MIMETYPE + "='" 
                                + Note.CONTENT_ITEM_TYPE + "'"
                        new String[] { contactId }, null); 
                if (notes.moveToFirst()) { 
                    do
                        int id = notes.getInt(notes.getColumnIndex(ContactsContract.CommonDataKinds.Note._ID));
                        String noteinfo = notes.getString(notes 
                                .getColumnIndex(Note.NOTE)); 
                         
                         
                        if(noteinfo==null||noteinfo.equals("")){
                            break;
                        }
                         
                        UserContent content=new UserContent();
                        content.setContentMark(context.getString(R.string.note_name));
                        content.setContentText(noteinfo);
                        content.setContentCategory(ActionCode.NORMAL_ACTION);
                        
                        setUserContentIndex(content,id+"",SourceCategory.SourceSystem.value);
                        listContents.add(content);
                         
                    } while (notes.moveToNext()); 
                
                 
                // 獲取網址 
                Cursor webSiteCr = resolver.query( 
                        Data.CONTENT_URI, 
                        new String[] { Website._ID,  Website.DATA ,Website.TYPE}, 
                        Data.CONTACT_ID + "=?" + " AND " + Website.MIMETYPE + "='" 
                                + Website.CONTENT_ITEM_TYPE + "'"
                        new String[] { contactId }, null); 
                if (webSiteCr.moveToFirst()) { 
                    do
                        int id = webSiteCr.getInt(webSiteCr.getColumnIndex(ContactsContract.CommonDataKinds.Website._ID));
                        int type=webSiteCr.getInt(webSiteCr.getColumnIndex(Website.TYPE));
                        String protocol = webSiteCr.getString(webSiteCr 
                                .getColumnIndex(Website.URL)); 
                        String data = webSiteCr 
                                .getString(webSiteCr.getColumnIndex(Website.DATA)); 
                         
                         
                        UserContent content=new UserContent();
                        content.setContentMark(context.getString(R.string.website_name));
                        content.setContentText(data);
                        content.setContentCategory(ActionCode.HYPERLINK_ACTION);
                         
                        setUserContentIndex(content,id+"",SourceCategory.SourceSystem.value);
                        listContents.add(content);
                    } while (IMs.moveToNext()); 
                
   
   
                // 獲取暱稱
                Cursor nicknames = resolver.query( 
                        Data.CONTENT_URI, 
                        new String[] { Nickname._ID, Nickname.NAME }, 
                        Data.CONTACT_ID + "=?" + " AND " + Data.MIMETYPE + "='" 
                                + Nickname.CONTENT_ITEM_TYPE + "'"
                        new String[] { contactId }, null); 
                if (nicknames.moveToFirst()) { 
                    do
                        int id = nicknames.getInt(nicknames.getColumnIndex(ContactsContract.CommonDataKinds.Nickname._ID));
                        String nickname = nicknames.getString(nicknames 
                                .getColumnIndex(Nickname.NAME)); 
                        
                         
                        if(nickname==null){
                            break;
                        }
                         
                        UserContent content=new UserContent();
                        content.setContentMark(context.getString(R.string.nick_name));
                        content.setContentText(nickname);
                        content.setContentCategory(ActionCode.NORMAL_ACTION);
                         
                        setUserContentIndex(content,id+"",SourceCategory.SourceSystem.value);
                        listContents.add(content);
                    } while (nicknames.moveToNext()); 
                }
                user.setListContent(listContents);
                listUser.add(user);
            } while (cur.moveToNext()); 
        
        return listUser;
    }
     
    /**
     * 修改和刪除聯繫人
     * @param user
     * @param f
     *
     *
     */
 
    @SuppressWarnings("unchecked")
    public void updateDelContent(User user, Boolean f) {
         
        UserIndex index=null;
         
        ForeignCollection<UserIndex> listIndex=user.getListIndex();
        for(UserIndex i:listIndex){
            if(SourceCategory.SourceSystem.value.equals(i.getSourceCategory())){
                index=i;
            }
        }
        if(index==null){
            return;
        }
        String sourceId=index.getSourceUserId();
        if(f == true){
            ArrayList ops = new ArrayList();
             
             // 更新family_name和given_name
            /*
            ops.add(ContentProviderOperation.newUpdate(ContactsContract.Data.CONTENT_URI)
                       .withSelection(ContactsContract.Data.CONTACT_ID + "=?" + " AND "
                         + ContactsContract.Data.MIMETYPE + "=?",
                          new String[]{user.getIndex().getSourceUserId(),ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE})
                          .withValue(ContactsContract.CommonDataKinds.StructuredName.FAMILY_NAME, user.getXing())
                           .withValue(ContactsContract.CommonDataKinds.StructuredName.GIVEN_NAME, user.getMing())
                            .build());
                  */
             
             
            ops.add(ContentProviderOperation.newUpdate(ContactsContract.Data.CONTENT_URI)
                       .withSelection(ContactsContract.Data.CONTACT_ID + "=?" + " AND "
                         + ContactsContract.Data.MIMETYPE + "=?",
                          new String[]{sourceId,ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE})
                          .withValue(ContactsContract.CommonDataKinds.StructuredName.DISPLAY_NAME, user.getMemberName())
                          
                            .build());
                 
             
            List<UserContent> list = user.getListContent();
            String category ;
            for(int i = 0; i< list.size(); i++){
                category = list.get(i).getContentCategory();
                System.out.println("category---"+category);
                if(category == ActionCode.PHONE_ACTION){
                //更新typeMobile
                       ops.add(ContentProviderOperation.newUpdate(ContactsContract.Data.CONTENT_URI)
                            .withSelection(ContactsContract.Data.CONTACT_ID +" =?  " + "  AND  "
                            +ContactsContract.Data.MIMETYPE + "=?" + " AND " +ContactsContract.CommonDataKinds.Organization.TYPE + "=?",
                            new String[]{sourceId,ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE,
                            String.valueOf(ContactsContract.CommonDataKinds.Phone.TYPE_MOBILE)})
                            .withValue(ContactsContract.CommonDataKinds.Phone.NUMBER, list.get(i).getContentText())
                            .build());
                         
                    }
                if(category == ActionCode.EMAIL_ACTION){
                    //更新email
                    ops.add(ContentProviderOperation.newUpdate(ContactsContract.Data.CONTENT_URI)
                            .withSelection(ContactsContract.Data.CONTACT_ID +" =?  " + "  AND  "
                                    +ContactsContract.Data.MIMETYPE + "=?" + " AND " +ContactsContract.CommonDataKinds.Email.TYPE + " =? ",
                                    new String[]{sourceId,ContactsContract.CommonDataKinds.Email.CONTENT_ITEM_TYPE,
                                    String.valueOf(ContactsContract.CommonDataKinds.Phone.TYPE_MOBILE)})
                                    .withValue(ContactsContract.CommonDataKinds.Email.DATA, list.get(i).getContentText())
                                    .build());
                     
                }
                if(category == ActionCode.ADDRESS_ACTION){
                    //更新地址信息
                    ops.add(ContentProviderOperation.newUpdate(ContactsContract.Data.CONTENT_URI)
                            .withSelection(ContactsContract.Data.CONTACT_ID + " =?  " " AND  "
                              +ContactsContract.Data.MIMETYPE + "  =? " + " =? " + ContactsContract.CommonDataKinds.StructuredPostal.TYPE + " =? ",
                              new String[]{sourceId, ContactsContract.CommonDataKinds.StructuredPostal.CONTENT_ITEM_TYPE,
                                    String.valueOf(ContactsContract.CommonDataKinds.StructuredPostal.TYPE_WORK)})
                                    .withValue(ContactsContract.CommonDataKinds.StructuredPostal.DATA, list.get(i).getContentText())
                                    .build());
                }
                     
                if(category == ActionCode.ORIGNIZE_ACTION){
                    //更行組織信息
                    ops.add(ContentProviderOperation.newUpdate(ContactsContract.Data.CONTENT_URI)
                            .withSelection(ContactsContract.Data.CONTACT_ID + " =? " + " AND "
                             +ContactsContract.Data.MIMETYPE + " =? " + " AND " + ContactsContract.CommonDataKinds.Organization.TYPE + " =? ",
                             new String[]{ sourceId, ContactsContract.CommonDataKinds.Organization.CONTENT_ITEM_TYPE,
                                    String.valueOf(ContactsContract.CommonDataKinds.Organization.TYPE_WORK)})
                                    .withValue(ContactsContract.CommonDataKinds.Organization.DATA, list.get(i).getContentText())
                                    .build());
                }
                 
                if(category == ActionCode.IM_ACTION){
                    //更新IM信息
                    ops.add(ContentProviderOperation.newUpdate(ContactsContract.Data.CONTENT_URI)
                            .withSelection(ContactsContract.Data.CONTACT_ID + " =? " + " AND "
                             +ContactsContract.Data.MIMETYPE + " =? " + " AND " + ContactsContract.CommonDataKinds.Im.TYPE+ " =? ",
                             new String[]{ sourceId, ContactsContract.CommonDataKinds.Im.CONTENT_ITEM_TYPE,
                                    String.valueOf(ContactsContract.CommonDataKinds.Im.TYPE_WORK)})
                                    .withValue(ContactsContract.CommonDataKinds.Organization.DATA, list.get(i).getContentText())
                                    .build());
                }
                 
                if(category == ActionCode.REMARK_ACTION){
                    //更新備註信息
                    ops.add(ContentProviderOperation.newUpdate(ContactsContract.Data.CONTENT_URI)
                            .withSelection(ContactsContract.Data.CONTACT_ID + " =? " + " AND "
                             +ContactsContract.Data.MIMETYPE + " =? ",
                             new String[]{ sourceId, ContactsContract.CommonDataKinds.Note.CONTENT_ITEM_TYPE,})
                                    .withValue(ContactsContract.CommonDataKinds.Note.DATA1, list.get(i).getContentText())
                                    .build());
                }
                 
                if(category == ActionCode.NICK_ACTION){
                    //更新暱稱
                    ops.add(ContentProviderOperation.newUpdate(ContactsContract.Data.CONTENT_URI)
                            .withSelection(ContactsContract.Data.CONTACT_ID + " =? " + " AND "
                             +ContactsContract.Data.MIMETYPE + " =? " + " AND " + ContactsContract.CommonDataKinds.Nickname.TYPE+ " =? ",
                             new String[]{ sourceId, ContactsContract.CommonDataKinds.Nickname.CONTENT_ITEM_TYPE,
                                    String.valueOf(ContactsContract.CommonDataKinds.Nickname.TYPE_CUSTOM)})
                                    .withValue(ContactsContract.CommonDataKinds.Nickname.DATA, list.get(i).getContentText())
                                    .build());
                }
                 
                if(category == ActionCode.HYPERLINK_ACTION){
                    //更新網址
                    ops.add(ContentProviderOperation.newUpdate(ContactsContract.Data.CONTENT_URI)
                            .withSelection(ContactsContract.Data.CONTACT_ID + " =? " + " AND "
                             +ContactsContract.Data.MIMETYPE + " =? " + " AND " + ContactsContract.CommonDataKinds.Website.TYPE+ " =? ",
                             new String[]{ sourceId, ContactsContract.CommonDataKinds.Website.CONTENT_ITEM_TYPE,
                                    String.valueOf(ContactsContract.CommonDataKinds.Website.TYPE_WORK)})
                                    .withValue(ContactsContract.CommonDataKinds.Website.DATA, list.get(i).getContentText())
                                    .build());
                }
                 
                 
                /*
            //更新company
            ops.add(ContentProviderOperation.newUpdate(ContactsContract.Data.CONTENT_URI)
                    .withSelection(ContactsContract.Data.CONTACT_ID + "=?"+"  AND  "
                    +ContactsContract.Data.MIMETYPE+"=?"+"  AND  "     
                    +ContactsContract.CommonDataKinds.Organization.TYPE_WORK, new String[]{
                    ContactsContract.CommonDataKinds.Organization.CONTENT_ITEM_TYPE,
                    String.valueOf(ContactsContract.CommonDataKinds.Organization.TYPE_WORK)})
                    //.withValue(ContactsContract.CommonDataKinds.Organization.COMPANY, user.get)
                    );
            */
             
            }
             try {
                  ContentProviderResult[] res = context.getContentResolver().applyBatch(ContactsContract.AUTHORITY, ops);
                      //  Log.i("contact", "android_id="+android_id+",firstName="+firstName+",lastName="+lastName);
                   //  appState.db.insertContactToTag(tagId,String.valueOf(contactId));
                     }
                  catch (RemoteException e){
                      e.printStackTrace();
                  } catch (OperationApplicationException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
            }
        }else{
            ContentResolver cr = context.getContentResolver();
            String where = ContactsContract.Data._ID +" = ?  ";
            String[] param = new String[]{ sourceId };
             
            ArrayList ops = new ArrayList();
            ops.add(ContentProviderOperation.newDelete(ContactsContract.RawContacts.CONTENT_URI)
                    .withSelection(where, param)
                    .build());
            try {
                cr.applyBatch(ContactsContract.AUTHORITY, ops);
            } catch (RemoteException e) {
                e.printStackTrace();
            } catch (OperationApplicationException e) {
                e.printStackTrace();
            }  
           }
        }
     
    /**
     * 刪除聯繫人屬性
     * @param dataId
     */
    public void deleteProperty(String dataId){
        ContentResolver cr = context.getContentResolver();
        String where = ContactsContract.Data._ID +" = ?  ";
        String[] param = new String[]{ dataId };
        cr.delete(ContactsContract.Data.CONTENT_URI, where, param);
    }
     
     
    public void updateInfo(){
        String dataId = "5";
        ContentResolver cr = context.getContentResolver();
        String where = ContactsContract.Data._ID +" = ?  ";
        String[] param = new String[]{ dataId };
        ContentValues values = new ContentValues();
        values.put(StructuredName.DISPLAY_NAME, "wang");
        cr.update(ContactsContract.Data.CONTENT_URI, values, where, param);
         
    }
     
    /**
     * 建立連個數據庫聯繫人的索引關係
     * @param content
     * @param uri
     */
    public void  setUserContentIndex(UserContent content,Uri uri,String source){
        long id = ContentUris.parseId(uri);
        setUserContentIndex(content,id+"",source);
    }
     
     
    public void setUserContentIndex(UserContent content,String id,String source){
        ContentIndex cindex=new ContentIndex();
        cindex.setSourceId(id);
        cindex.setPolyId("1");
        cindex.setSourceCategory(source);
        content.getUpdateIndex().add(cindex);
    }
}
發佈了8 篇原創文章 · 獲贊 6 · 訪問量 1萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章