Android 异步开发之 AsyncQueryHandler 批量添加联系人

AsyncQueryHandler

  官方解释是一个异步帮助类(A helper class to help make handling asynchronouContentResolver queries easier.) 。这个类的主要作用就是异步对DB数据库进行操作,加快其数据处理的速度(这个非常重要,特别是大容量的数据处理时,例如几千联系人的数据读取,按正常的处理速度会非常的慢,使用AsyncQueryHandler,这就会大大的加快速度,增加用户的良好体验)。


AsyncQueryHandler重要的方法:

 

final void startDelete(int token, Object cookie, Uri uri, String selection, String[] selectionArgs)
This method begins an asynchronous delete.
final void startInsert(int token, Object cookie, Uri uri, ContentValues initialValues)
This method begins an asynchronous insert.
void startQuery(int token, Object cookie, Uri uri, String[] projection, String selection, String[] selectionArgs, String orderBy)
This method begins an asynchronous query.
final void startUpdate(int token, Object cookie, Uri uri, ContentValues values, String selection, String[] selectionArgs)
This method begins an asynchronous update.
显然,从方法的名字,我们可以看出,这是使用异步方式对DB数据库进行基本的增,删,改,查。

 

 

void onDeleteComplete(int token, Object cookie, int result)
Called when an asynchronous delete is completed.
void onInsertComplete(int token, Object cookie, Uri uri)
Called when an asynchronous insert is completed.
void onQueryComplete(int token, Object cookie, Cursor cursor)
Called when an asynchronous query is completed.
void onUpdateComplete(int token, Object cookie, int result)
Called when an asynchronous update is completed.
这几个方法,分别对应于上面四个异步操作时的回调方法。

 


AsyncQueryHandler的一个应用:读取电话联系人的数据信息

 

[java]  view plain copy
 
  1. public class TestAsyncQueryHandler extends Activity {  
  2.       
  3.     private static final String NAME = "name", NUMBER = "number", SORT_KEY = "sort_key";  
  4.       
  5.     private List<ContentValues> listData;  
  6.     private AsyncQueryHandler asyncQuery;    
  7.       
  8.     private ListView personList;  
  9.     private BaseAdapter adapter;    
  10.     
  11.     @Override    
  12.     public void onCreate(Bundle savedInstanceState) {    
  13.         super.onCreate(savedInstanceState);    
  14.           
  15.         setContentView(R.layout.main);    
  16.           
  17.         personList = (ListView) findViewById(R.id.list_view);        
  18.         asyncQuery = new MyAsyncQueryHandler(getContentResolver());  
  19.         //异步读取联系人的信息  
  20.         asyncQueryContact();         
  21.     }    
  22.     
  23.   
  24.     private void asyncQueryContact() {  
  25.         // TODO Auto-generated method stub  
  26.         Uri uri = Uri.parse("content://com.android.contacts/data/phones");    
  27.         String[] projection = { "_id""display_name""data1""sort_key" };    
  28.         asyncQuery.startQuery(0null, uri, projection, nullnull,"sort_key COLLATE LOCALIZED asc");  
  29.     }  
  30.   
  31.   
  32.     private class MyAsyncQueryHandler extends AsyncQueryHandler {    
  33.     
  34.         public MyAsyncQueryHandler(ContentResolver cr) {    
  35.             super(cr);    
  36.     
  37.         }    
  38.     
  39.         @Override    
  40.         protected void onQueryComplete(int token, Object cookie, Cursor cursor) {    
  41.             if (cursor != null && cursor.getCount() > 0) {    
  42.                 listData = new ArrayList<ContentValues>();    
  43.                 //cursor.moveToFirst();    
  44.                 for (int i = 0; i < cursor.getCount(); i++) {  
  45.                     ContentValues cv = new ContentValues();    
  46.                     cursor.moveToPosition(i);    
  47.                     String name = cursor.getString(1);    
  48.                     String number = cursor.getString(2);    
  49.                     String sortKey = cursor.getString(3);  
  50.                     if (number.startsWith("+86")) {    
  51.                         cv.put(NAME, name);    
  52.                         //process (+86)  
  53.                         cv.put(NUMBER, number.substring(3));    
  54.                         cv.put(SORT_KEY, sortKey);    
  55.                     } else {    
  56.                         cv.put(NAME, name);    
  57.                         cv.put(NUMBER, number);    
  58.                         cv.put(SORT_KEY, sortKey);    
  59.                     }    
  60.                     listData.add(cv);    
  61.                 }    
  62.                 if (listData.size() > 0) {    
  63.                     setAdapter(listData);    
  64.                 }    
  65.                 cursor.close();  
  66.             }    
  67.         }    
  68.     
  69.     }    
  70.     
  71.     private void setAdapter(List<ContentValues> listData) {  
  72.         adapter = new ListAdapter(this, listData);  
  73.         personList.setAdapter(adapter);    
  74.     
  75.     }  
  76.       
  77.       
  78.     private class ListAdapter extends BaseAdapter {  
  79.           
  80.          private LayoutInflater inflater;    
  81.          private List<ContentValues> list;  
  82.           
  83.         public ListAdapter(Context context, List<ContentValues> list) {  
  84.             this.inflater = LayoutInflater.from(context);  
  85.             this.list = list;             
  86.         }  
  87.           
  88.         @Override  
  89.         public int getCount() {  
  90.             return list.size();  
  91.         }  
  92.   
  93.         @Override  
  94.         public Object getItem(int position) {  
  95.             return list.get(position);  
  96.         }  
  97.   
  98.         @Override  
  99.         public long getItemId(int position) {  
  100.             return position;  
  101.         }  
  102.           
  103.         @Override  
  104.         public View getView(int position, View convertView, ViewGroup parent) {  
  105.             ViewHolder holder;  
  106.             if (convertView == null) {    
  107.                 convertView = inflater.inflate(R.layout.list_item, null);  
  108.                 holder = new ViewHolder();    
  109.                 holder.name = (TextView) convertView.findViewById(R.id.name);    
  110.                 holder.number = (TextView) convertView.findViewById(R.id.number);    
  111.                 convertView.setTag(holder);    
  112.             } else {    
  113.                 holder = (ViewHolder) convertView.getTag();    
  114.             }    
  115.               
  116.             ContentValues cv = list.get(position);    
  117.             holder.name.setText(cv.getAsString(NAME));  
  118.             holder.number.setText(cv.getAsString(NUMBER));  
  119.   
  120.             return convertView;    
  121.         }  
  122.           
  123.         private class ViewHolder {   
  124.             TextView name;    
  125.             TextView number;  
  126.         }  
  127.           
  128.     }  
  129.        
  130. }    
  

 

  这个例子,只是使用了AsyncQueryHandler类中的异步查询方法,其它的方法,也是类似,大家可以自己尝试。


源代码下载地址:

           http://download.csdn.net/detail/hfreeman2011/5040647


参考资料:

1.android异步的几种方式

http://ericchan2012.iteye.com/blog/1673929

2.官方文档

http://developer.android.com/reference/android/content/AsyncQueryHandler.html

3.android快速滑动列表 首字母提示

http://download.csdn.net/detail/j1582830/4010012

Android 异步开发之 AsyncQueryHandler
 
批量添加联系人
 <!-- 添加联系人权限 -->

    <uses-permission android:name="android.permission.READ_CONTACTS" />

    <uses-permission android:name="android.permission.WRITE_CONTACTS" />

    <!-- 加入SDCARD的删除文件权限 -->

    <uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS" />

    <!-- 加入SDCARD的写入数据权限 -->

    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

<!-- 联系人相关的uri -->
content://com.android.contacts/contacts 操作的数据是联系人信息Uri
content://com.android.contacts/data/phones 联系人电话Uri
content://com.android.contacts/data/emails 联系人Email Uri   

public class MainActivity extends Activity {



    @Override

    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);

        if (!Environment.getExternalStorageState().equals(

                Environment.MEDIA_MOUNTED)) {

            Toast.makeText(getApplicationContext(), "没有sdcard",0).show();

            return;

        }

        

        final String path = Environment.getExternalStorageDirectory()

                .toString() + "/addcont/";

        ((TextView)findViewById(R.id.tv)).setText("文件存放的目录:"+path);

        

        findViewById(R.id.btn).setOnClickListener(new OnClickListener() {

            @Override

            public void onClick(View v) {

                if (Environment.getExternalStorageState().equals(

                        Environment.MEDIA_MOUNTED)) {

                    File dirFire = new File(path);

                    if (!dirFire.exists()) {

                        dirFire.mkdirs();

                        return;

                    }

                    File[] files = dirFire.listFiles(new FileFilter() {

                        public boolean accept(File arg0) {

                            if (arg0.getName().endsWith(".txt")) {// 选择txt文件

                                return true;

                            }

                            return false;

                        }

                    });

                    if (files != null && files.length > 0) {

                        for (File file : files) {

                            try {

                                FileInputStream is = null; // 输入流读取文件

                                BufferedReader dr = null; // 读行

                                is = new FileInputStream(file);

                                dr = new BufferedReader(new InputStreamReader(is));

                                String totalTrans = null;

                                List<Tb_contacts> contacts = new ArrayList<Tb_contacts>();

                                while ((totalTrans = dr.readLine()) != null) {

                                    if (totalTrans.contains("|")) {

                                        String[] conStrings = totalTrans.trim().split("|");

                                        contacts.add(new Tb_contacts(conStrings[1], conStrings[0]));

                                    } else {

                                        contacts.add(new Tb_contacts("", totalTrans.trim()));

                                    }

                                }

                                BatchAddContact(contacts);

                                dr.close();

                                is.close();

                            }  catch (Exception e) {

                                e.printStackTrace();

                                Toast.makeText(getApplicationContext(), "导入联系人失败",0).show();

                            }

                        }

                    }



                } else {



                }



            }

        });

    }



    public void BatchAddContact(List<Tb_contacts> list) {

        try {

            ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>();

            int rawContactInsertIndex = 0;

            for (Tb_contacts contact : list) {

                rawContactInsertIndex = ops.size(); // 有了它才能给真正的实现批量添加



                ops.add(ContentProviderOperation

                        .newInsert(RawContacts.CONTENT_URI)

                        .withValue(RawContacts.ACCOUNT_TYPE, null)

                        .withValue(RawContacts.ACCOUNT_NAME, null)

                        .withYieldAllowed(true).build());



                // 添加姓名

                ops.add(ContentProviderOperation

                        .newInsert(ContactsContract.Data.CONTENT_URI)

                        .withValueBackReference(Data.RAW_CONTACT_ID,

                                rawContactInsertIndex)

                        .withValue(Data.MIMETYPE,

                                StructuredName.CONTENT_ITEM_TYPE)

                        .withValue(StructuredName.DISPLAY_NAME,

                                contact.getName()).withYieldAllowed(true)

                        .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, contact.getNumber())

                        .withValue(Phone.TYPE, Phone.TYPE_MOBILE)

                        .withValue(Phone.LABEL, "").withYieldAllowed(true)

                        .build());

            }

            if (ops != null) {



                // 真正添加

                ContentProviderResult[] results = getContentResolver()

                        .applyBatch(ContactsContract.AUTHORITY, ops);

                Log.i("tag", "----------------------------------" + results);

                for (ContentProviderResult result : results) {



                }

            }

        } catch (RemoteException e) {

            e.printStackTrace();

        } catch (OperationApplicationException e) {

            e.printStackTrace();

        }

    }



    private class Tb_contacts {

        private String name;

        private String number;



        public Tb_contacts(String name, String number) {

            super();

            this.name = name;

            this.number = number;

        }



        public String getName() {

            return name;

        }



        public void setName(String name) {

            this.name = name;

        }



        public String getNumber() {

            return number;

        }



        public void setNumber(String number) {

            this.number = number;

        }

    }

    

}
[mw_shl_code=java,true]/**

         * 添加联系人

         */

        private void insertNewContact(ContactItemList contactItemList) {

                for (int rawContactInsertIndex = 0; rawContactInsertIndex < contactItemList.size(); rawContactInsertIndex++) {



                        ContactItem contactItem = contactItemList.get(rawContactInsertIndex);

                        String name = contactItem.getName();

                        String nickname = contactItem.getNickName();

                        String company = contactItem.getUnit();

                        String post = contactItem.getBusiness();

                        String mobilephone = contactItem.getCellPhone();

                        String hometel = contactItem.getHomeTel();

                        String officetel = contactItem.getOfficeTel();

                        String fax = contactItem.getFax();

                        String email = contactItem.getEmail();

                        String qq = contactItem.getQq();

                        String msn = contactItem.getMsn();

                        Date birthday = contactItem.getBirthday();

                        String remark = contactItem.getRemark();



                        ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>();



                        // 在名片表插入一个新名片

                        ops.add(ContentProviderOperation.newInsert(ContactsContract.RawContacts.CONTENT_URI).withValue(ContactsContract.RawContacts.ACCOUNT_TYPE, null).withValue(ContactsContract.RawContacts._ID, 0).withValue(ContactsContract.RawContacts.ACCOUNT_NAME, null).withValue(ContactsContract.RawContacts.AGGREGATION_MODE, ContactsContract.RawContacts.AGGREGATION_MODE_DISABLED).build());



                        // 姓名

                        if (StringUtils.isNotEmpty(name)) {

                                // System.out.println("name: " + name);

                                ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI).withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, 0).withValue(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE).withValue(ContactsContract.CommonDataKinds.StructuredName.DISPLAY_NAME, name).build());

                        }



                        // 昵称

                        if (StringUtils.isNotEmpty(nickname)) {

                                // System.out.println("nickname: " + nickname);

                                ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI).withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, 0).withValue(ContactsContract.Data.MIMETYPE, Nickname.CONTENT_ITEM_TYPE).withValue(Nickname.NAME, nickname).withValue(Nickname.TYPE, Nickname.TYPE_CUSTOM).build());

                        }



                        // 公司

                        if (StringUtils.isNotEmpty(company)) {

                                // System.out.println("company: " + company);

                                ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI).withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, 0).withValue(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.Organization.CONTENT_ITEM_TYPE).withValue(ContactsContract.CommonDataKinds.Organization.COMPANY, company).withValue(ContactsContract.CommonDataKinds.Organization.TYPE, ContactsContract.CommonDataKinds.Organization.TYPE_WORK).build());

                        }



                        // 职位

                        if (StringUtils.isNotEmpty(post)) {

                                // System.out.println("post: " + post);

                                ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI).withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, 0).withValue(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.Organization.CONTENT_ITEM_TYPE).withValue(ContactsContract.CommonDataKinds.Organization.TITLE, post).withValue(ContactsContract.CommonDataKinds.Organization.TYPE, ContactsContract.CommonDataKinds.Organization.TYPE_WORK).build());

                        }



                        // 手机

                        if (StringUtils.isNotEmpty(mobilephone)) {

                                // System.out.println("mobilephone: " + mobilephone);

                                ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI).withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, 0).withValue(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE).withValue(ContactsContract.CommonDataKinds.Phone.NUMBER, mobilephone).withValue(ContactsContract.CommonDataKinds.Phone.TYPE, Phone.TYPE_MOBILE).build());

                        }



                        // 家庭电话

                        if (StringUtils.isNotEmpty(hometel)) {

                                // System.out.println("hometel: " + hometel);

                                ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI).withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, 0).withValue(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE).withValue(ContactsContract.CommonDataKinds.Phone.NUMBER, hometel).withValue(ContactsContract.CommonDataKinds.Phone.TYPE, Phone.TYPE_HOME).build());

                        }



                        // 办公电话

                        if (StringUtils.isNotEmpty(officetel)) {

                                // System.out.println("officetel: " + officetel);

                                ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI).withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, 0).withValue(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE).withValue(ContactsContract.CommonDataKinds.Phone.NUMBER, officetel).withValue(ContactsContract.CommonDataKinds.Phone.TYPE, Phone.TYPE_WORK).build());

                        }



                        // 传真

                        if (StringUtils.isNotEmpty(fax)) {

                                // System.out.println("fax: " + fax);

                                ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI).withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, 0).withValue(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE).withValue(ContactsContract.CommonDataKinds.Phone.NUMBER, fax).withValue(ContactsContract.CommonDataKinds.Phone.TYPE, Phone.TYPE_FAX_WORK).build());

                        }



                        // 邮箱

                        if (StringUtils.isNotEmpty(email)) {

                                // System.out.println("email: " + email);

                                ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI).withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, 0).withValue(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.Email.CONTENT_ITEM_TYPE).withValue(ContactsContract.CommonDataKinds.Email.DATA, email).withValue(ContactsContract.CommonDataKinds.Email.TYPE, Email.TYPE_WORK).build());

                        }



                        // QQ

                        if (StringUtils.isNotEmpty(qq)) {

                                // System.out.println("qq: " + qq);

                                ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI).withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, 0).withValue(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.Im.CONTENT_ITEM_TYPE).withValue(ContactsContract.CommonDataKinds.Im.DATA1, qq).withValue(ContactsContract.CommonDataKinds.Im.PROTOCOL, ContactsContract.CommonDataKinds.Im.PROTOCOL_QQ).build());

                        }



                        // MSN

                        if (StringUtils.isNotEmpty(msn)) {

                                // System.out.println("msn: " + msn);

                                ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI).withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, 0).withValue(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.Im.CONTENT_ITEM_TYPE).withValue(ContactsContract.CommonDataKinds.Im.DATA1, msn).withValue(ContactsContract.CommonDataKinds.Im.PROTOCOL, ContactsContract.CommonDataKinds.Im.PROTOCOL_MSN).build());

                        }



                        // 备注

                        if (StringUtils.isNotEmpty(remark)) {

                                // System.out.println("remark: " + remark);

                                ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI).withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, 0).withValue(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.Note.CONTENT_ITEM_TYPE).withValue(ContactsContract.CommonDataKinds.Note.NOTE, remark).build());

                        }



                        try {

                                ContentProviderResult[] result = context.getContentResolver().applyBatch(ContactsContract.AUTHORITY, ops);

                                for (ContentProviderResult cpr : result) {

                                        System.out.println(cpr.uri.toString());

                                }

                        } catch (OperationApplicationException e) {

                                Log.e(TAG, e.getMessage(), e);

                        } catch (RemoteException e) {

                                Log.e(TAG, e.getMessage(), e);

                        }

                }



        }[/mw_shl_code]
View Code
 
http://www.eoeandroid.com/forum.php?mod=viewthread&tid=327658
//自己解决了~ 把这一句里的

// 在名片表插入一个新名片                       ops.add(ContentProviderOperation.newInsert(ContactsContract.RawContacts.CONTENT_URI).withValue(ContactsContract.RawContacts.ACCOUNT_TYPE, null).withValue(ContactsContract.RawContacts._ID, 0).withValue(ContactsContract.RawContacts.ACCOUNT_NAME, null).withValue(ContactsContract.RawContacts.AGGREGATION_MODE, ContactsContract.RawContacts.AGGREGATION_MODE_DISABLED).build());





withValue(ContactsContract.RawContacts._ID, 0).去掉就可以了~
View Code
package com.ljq.contact;



import java.util.ArrayList;



import android.content.ContentProviderOperation;

import android.content.ContentProviderResult;

import android.content.ContentResolver;

import android.content.ContentUris;

import android.content.ContentValues;

import android.database.Cursor;

import android.net.Uri;

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.Phone;

import android.provider.ContactsContract.CommonDataKinds.StructuredName;

import android.test.AndroidTestCase;

import android.util.Log;



public class ContactTest extends AndroidTestCase{

    private static final String TAG = "ContactTest";

    

    /**

     * 获取通讯录中联系人

     */

    public void testGetContact(){

        ContentResolver contentResolver = this.getContext().getContentResolver();

        Uri uri = Uri.parse("content://com.android.contacts/contacts");

        Cursor cursor = contentResolver.query(uri, null, null, null, null);

        while(cursor.moveToNext()){

            // 获取联系人姓名

            StringBuilder sb = new StringBuilder();

            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 phone = phones.getString(phones.getColumnIndex("data1")); 

                sb.append(",phone=").append(phone);

            }

            

            //获取联系人email

            Cursor emails = contentResolver.query(ContactsContract.CommonDataKinds.Email.CONTENT_URI,  

                       null,  

                       ContactsContract.CommonDataKinds.Email.CONTACT_ID + " = " + contactId,  

                       null, null); 

            while(emails.moveToNext()){

                String email = emails.getString(emails.getColumnIndex("data1")); 

                sb.append(",email=").append(email);

            }

            Log.i(TAG, sb.toString());

        }

    }



    /**

     * 首先向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);

        long rawContactId = ContentUris.parseId(rawContactUri);

        

        //往data表入姓名数据

        values.clear();

        values.put(Data.RAW_CONTACT_ID, rawContactId);

        values.put(Data.MIMETYPE, StructuredName.CONTENT_ITEM_TYPE);

        values.put(StructuredName.GIVEN_NAME, "zhangsan");

        this.getContext().getContentResolver().insert(

                android.provider.ContactsContract.Data.CONTENT_URI, values);

        

        //往data表入电话数据

        values.clear();

        values.put(android.provider.ContactsContract.Contacts.Data.RAW_CONTACT_ID, rawContactId);

        values.put(Data.MIMETYPE, Phone.CONTENT_ITEM_TYPE);

        values.put(Phone.NUMBER, "5554");

        values.put(Phone.TYPE, Phone.TYPE_MOBILE);

        this.getContext().getContentResolver().insert(

                android.provider.ContactsContract.Data.CONTENT_URI, values);



        //往data表入Email数据

        values.clear();

        values.put(android.provider.ContactsContract.Contacts.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);

    }

    

    /**

     * 批量添加联系人,处于同一个事务中

     */

    public void testSave() throws Throwable{

        //文档位置:reference\android\provider\ContactsContract.RawContacts.html

        ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>();

        int rawContactInsertIndex = 0;

        ops.add(ContentProviderOperation.newInsert(RawContacts.CONTENT_URI)

                .withValue(RawContacts.ACCOUNT_TYPE, null)

                .withValue(RawContacts.ACCOUNT_NAME, null)

                .build());

        

        //文档位置:reference\android\provider\ContactsContract.Data.html

        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, "lisi")

                .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, "5556")

                 .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());

        }

    }

    

}
View Code

 

 

 
 
 

你可能感兴趣的:(android)