Android--读取通讯录并添加联系人

1.加入读写权限

Xhtml代码
  1. <uses-permission android:name="android.permission.READ_CONTACTS" />  
  2. <uses-permission android:name="android.permission.WRITE_CONTACTS" />  

联系人信息Uri:

content://com.android.contacts/contacts

联系人电话Uri:

content://com.android.contacts/data/phones

联系人Email Uri:

content://com.android.contacts/data/emails


(推荐)也可以这样获取联系人信息Uri:Uri uri = ContactsContract.Contacts.CONTENT_URI;



2.查询与添加联系人的操作(单元测试用例)


    public class ContactTest extends AndroidTestCase   
    {  
        private static final String TAG = "ContactTest";  
          
        /** 
         * 获取通讯录中所有联系人的简单信息 
         * @throws Throwable 
         */  
        public void testGetAllContact() throws Throwable  
        {  
            //获取联系人信息的Uri  
            Uri uri =  ContactsContract.Contacts.CONTENT_URI;  
            //获取ContentResolver  
            ContentResolver contentResolver = this.getContext().getContentResolver();  
            //查询数据,返回Cursor  
            Cursor cursor = contentResolver.query(uri, null, null, null, null);  
            while(cursor.moveToNext())  
            {  
                StringBuilder sb = new StringBuilder();  
                //获取联系人的ID  
                String contactId = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));    
                //获取联系人的姓名  
                String name = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));   
                //构造联系人信息  
                sb.append("contactId=").append(contactId).append(",Name=").append(name);  
                //查询电话类型的数据操作  
                Cursor phones = contentResolver.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,    
                        null,    
                        ContactsContract.CommonDataKinds.Phone.CONTACT_ID +" = "+ contactId,    
                        null, null);    
                while(phones.moveToNext())  
                {  
                    String phoneNumber = phones.getString(phones.getColumnIndex(  
                            ContactsContract.CommonDataKinds.Phone.NUMBER));  
                    //添加Phone的信息  
                    sb.append(",Phone=").append(phoneNumber);  
                }  
                phones.close();  
                  
                //查询Email类型的数据操作  
                Cursor emails = contentResolver.query(ContactsContract.CommonDataKinds.Email.CONTENT_URI,    
                           null,    
                           ContactsContract.CommonDataKinds.Email.CONTACT_ID + " = " + contactId,    
                           null, null);    
                while (emails.moveToNext())   
                {    
                    String emailAddress = emails.getString(emails.getColumnIndex(  
                            ContactsContract.CommonDataKinds.Email.DATA));  
                    //添加Email的信息  
                    sb.append(",Email=").append(emailAddress);  
                }   
                emails.close();  
                Log.i(TAG, sb.toString());  
            }  
            cursor.close();  
        }  
          
        /**添加联系人的第一种方法: 
         * 首先向RawContacts.CONTENT_URI执行一个空值插入,目的是获取系统返回的rawContactId  
         * 这时后面插入data表的依据,只有执行空值插入,才能使插入的联系人在通讯录里面可见 
         */  
        public void testInsert()   
        {  
            ContentValues values = new ContentValues();  
            //首先向RawContacts.CONTENT_URI执行一个空值插入,目的是获取系统返回的rawContactId   
            Uri rawContactUri = this.getContext().getContentResolver().insert(RawContacts.CONTENT_URI, values);  
            //获取id  
            long rawContactId = ContentUris.parseId(rawContactUri);  
            //往data表入姓名数据  
            values.clear();  
            values.put(Data.RAW_CONTACT_ID, rawContactId); //添加id  
            values.put(Data.MIMETYPE, StructuredName.CONTENT_ITEM_TYPE);//添加内容类型(MIMETYPE)  
            values.put(StructuredName.GIVEN_NAME, "凯风自南");//添加名字,添加到first name位置  
            this.getContext().getContentResolver().insert(android.provider.ContactsContract.Data.CONTENT_URI, values);  
            //往data表入电话数据  
            values.clear();  
            values.put(Data.RAW_CONTACT_ID, rawContactId);  
            values.put(Data.MIMETYPE, Phone.CONTENT_ITEM_TYPE);  
            values.put(Phone.NUMBER, "13921009789");  
            values.put(Phone.TYPE, Phone.TYPE_MOBILE);  
            this.getContext().getContentResolver().insert(android.provider.ContactsContract.Data.CONTENT_URI, values);  
            //往data表入Email数据  
            values.clear();  
            values.put(Data.RAW_CONTACT_ID, rawContactId);  
            values.put(Data.MIMETYPE, Email.CONTENT_ITEM_TYPE);  
            values.put(Email.DATA, "[email protected]");  
            values.put(Email.TYPE, Email.TYPE_WORK);  
            this.getContext().getContentResolver().insert(android.provider.ContactsContract.Data.CONTENT_URI, values);  
        }  
          
        /**添加联系人的第二种方法: 
         * 批量添加联系人 
         * @throws Throwable 
         */  
        public void testSave() throws Throwable  
        {  
            //官方文档位置:reference\android\provider\ContactsContract.RawContacts.html  
            //建立一个ArrayList存放批量的参数  
            ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>();  
            int rawContactInsertIndex = ops.size();  
            ops.add(ContentProviderOperation.newInsert(RawContacts.CONTENT_URI)  
                    .withValue(RawContacts.ACCOUNT_TYPE, null)  
                    .withValue(RawContacts.ACCOUNT_NAME, null)  
                    .build());  
            //官方文档位置:reference\android\provider\ContactsContract.Data.html  
            //withValueBackReference后退引用前面联系人的id  
            ops.add(ContentProviderOperation.newInsert(android.provider.ContactsContract.Data.CONTENT_URI)  
                    .withValueBackReference(Data.RAW_CONTACT_ID, rawContactInsertIndex)  
                    .withValue(Data.MIMETYPE, StructuredName.CONTENT_ITEM_TYPE)  
                    .withValue(StructuredName.GIVEN_NAME, "小明")  
                    .build());  
            ops.add(ContentProviderOperation.newInsert(android.provider.ContactsContract.Data.CONTENT_URI)  
                     .withValueBackReference(Data.RAW_CONTACT_ID, rawContactInsertIndex)  
                     .withValue(Data.MIMETYPE, Phone.CONTENT_ITEM_TYPE)  
                     .withValue(Phone.NUMBER, "13671323809")  
                     .withValue(Phone.TYPE, Phone.TYPE_MOBILE)  
                     .withValue(Phone.LABEL, "手机号")  
                     .build());  
            ops.add(ContentProviderOperation.newInsert(android.provider.ContactsContract.Data.CONTENT_URI)  
                     .withValueBackReference(Data.RAW_CONTACT_ID, rawContactInsertIndex)  
                     .withValue(Data.MIMETYPE, Email.CONTENT_ITEM_TYPE)  
                     .withValue(Email.DATA, "[email protected]")  
                     .withValue(Email.TYPE, Email.TYPE_WORK)  
                     .build());  
            ContentProviderResult[] results = this.getContext().getContentResolver()  
                .applyBatch(ContactsContract.AUTHORITY, ops);  
            for(ContentProviderResult result : results)  
            {  
                Log.i(TAG, result.uri.toString());  
            }  
        }  
    }  


你可能感兴趣的:(通讯录)