官方解释是一个异步帮助类(A helper class to help make handling asynchronous ContentResolver
queries easier.) 。这个类的主要作用就是异步对DB数据库进行操作,加快其数据处理的速度(这个非常重要,特别是大容量的数据处理时,例如几千联系人的数据读取,按正常的处理速度会非常的慢,使用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.
|
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类中的异步查询方法,其它的方法,也是类似,大家可以自己尝试。
源代码下载地址:
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]
//自己解决了~ 把这一句里的 // 在名片表插入一个新名片 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).去掉就可以了~
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()); } } }