使用Contact数据模型来批量插入联系人(下)
来源:互联网 发布:耳机延长线 知乎 编辑:程序博客网 时间:2024/05/03 02:29
上文接《使用Contact数据模型来批量插入联系人(上)》
文件5
ContactPersistTask.java文件
package com.teleca.robin.Contact;import java.util.ArrayList;import java.util.Random;import android.app.Activity;import android.app.ProgressDialog;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.os.AsyncTask;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.Phone;import android.provider.ContactsContract.CommonDataKinds.StructuredName;import android.util.Log;import android.widget.Toast;import com.teleca.robin.model.EntityDelta;import com.teleca.robin.model.EntitySet;import com.teleca.robin.model.EntityDelta.ValuesDelta;public class ContactPersistTask extends AsyncTask<Integer, Integer, Integer> {private ProgressDialog mProgress;Context context;DialogResolver dialogResolver;final static String tag="robin";public ContactPersistTask(DialogResolver dialogResolver) {this.dialogResolver = dialogResolver;this.context = (Activity) dialogResolver;}/** {@inheritDoc} */@Overrideprotected void onPreExecute() {mProgress = new ProgressDialog((Activity) context);mProgress.setTitle(R.string.insert_title);mProgress.setMessage(context.getText(R.string.insert_tip));mProgress.setProgress(0);mProgress.setMax(100);mProgress.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);dialogResolver.showDialog(mProgress);}public static EntitySet generateRawContactSet(int count) {EntityDelta rawContact = generateRawContact();EntitySet entitySet = EntitySet.fromSingle(rawContact);for (int i = 1; i < count; i++) {entitySet.add(generateRawContact());}return entitySet;}public static EntityDelta generateRawContact() {String accountType = null;String accountName = null;ContentValues contentValues = new ContentValues();contentValues.put(RawContacts.ACCOUNT_TYPE, accountType);contentValues.put(RawContacts.ACCOUNT_NAME, accountName);ValuesDelta values = ValuesDelta.fromAfter(contentValues);EntityDelta rawContact = new EntityDelta(values);//nameContentValues nameValues = new ContentValues();nameValues.put(Data.MIMETYPE, StructuredName.CONTENT_ITEM_TYPE);nameValues.put(StructuredName.FAMILY_NAME, generateFamilyName());nameValues.put(StructuredName.GIVEN_NAME, generateGivenName());rawContact.addEntry(ValuesDelta.fromAfter(nameValues));//phone numberContentValues phoneValues = new ContentValues();phoneValues.put(Data.MIMETYPE, Phone.CONTENT_ITEM_TYPE);phoneValues.put(Phone.NUMBER, generateMobilePhone());phoneValues.put(Phone.TYPE, Phone.TYPE_CUSTOM);rawContact.addEntry(ValuesDelta.fromAfter(phoneValues));phoneValues = new ContentValues();phoneValues.put(Data.MIMETYPE, Phone.CONTENT_ITEM_TYPE);phoneValues.put(Phone.NUMBER, generateHomePhone());phoneValues.put(Phone.TYPE, Phone.TYPE_HOME);rawContact.addEntry(ValuesDelta.fromAfter(phoneValues));ContentValues emailValues = new ContentValues();emailValues.put(Data.MIMETYPE, Email.CONTENT_ITEM_TYPE);emailValues.put(Email.ADDRESS, generateEmail());emailValues.put(Email.TYPE, Email.TYPE_HOME);rawContact.addEntry(ValuesDelta.fromAfter(emailValues));emailValues = new ContentValues();emailValues.put(Data.MIMETYPE, Email.CONTENT_ITEM_TYPE);emailValues.put(Email.ADDRESS, generateEmail());emailValues.put(Email.TYPE, Email.TYPE_MOBILE);rawContact.addEntry(ValuesDelta.fromAfter(emailValues));//group/** ContentValues groupValues=new ContentValues();* groupValues.put(Data.MIMETYPE, GroupMembership.CONTENT_ITEM_TYPE);* groupValues.put(GroupMembership.GROUP_ROW_ID, "0");*///IMContentValues imValues = new ContentValues();imValues.put(Data.MIMETYPE, Im.CONTENT_ITEM_TYPE);imValues.put(Im.DATA, generateQQ());imValues.put(Im.TYPE, Im.TYPE_CUSTOM);imValues.put(Im.PROTOCOL, Im.PROTOCOL_QQ);rawContact.addEntry(ValuesDelta.fromAfter(imValues));imValues = new ContentValues();imValues.put(Data.MIMETYPE, Im.CONTENT_ITEM_TYPE);imValues.put(Im.DATA, generateMSN());imValues.put(Im.TYPE, Im.TYPE_WORK);imValues.put(Im.PROTOCOL, Im.PROTOCOL_MSN);rawContact.addEntry(ValuesDelta.fromAfter(imValues));// Postal address/** ContentValues postalAddressValues=new ContentValues();* postalAddressValues.put(Data.MIMETYPE,* StructuredPostal.CONTENT_ITEM_TYPE);* postalAddressValues.put(StructuredPostal* .TYPE,StructuredPostal.TYPE_HOME);*/return rawContact;}final static String familyNames[] = { "hu", "yang", "wang", "li", "zhang","long", "zhu", "zheng", "tao", "liu", "wen", "zhao", "zu", "xu","zhou", "ling", "nu", "luo", "wuang", "liao", "yuan", "sun", "he","guo", "nuo", "bai" };final static Random random = new Random(System.currentTimeMillis());public static String generateFamilyName() {int len = familyNames.length;int index = random.nextInt() % len;index = (index + len) % len;return familyNames[index];}final static String giveNames[] = { "bing", "wei", "qiang", "chao", "qing","yang", "xing chi", "bin", "qi chao", "guo wei" ,"xi","tao","guo rong"};public static String generateGivenName() {int len = giveNames.length;int index = random.nextInt() % len;index = (index + len) % len;int number = random.nextInt() % 100;if (number < 0)return giveNames[index];elsereturn giveNames[index] + number;}public static String generateMSN() {int number = random.nextInt() % 100;if (number < 0) {return "hubinforever@163.com";} else {return "hubinforever" + number + "@163.com";}}public static String generateQQ() {int number = random.nextInt() % 1000;if (number < 0) {return "248600690";} else {return "248600" + number;}}final static String kEmailPrefix[] = { "hh", "hubing", "abc" };final static String kEmailSuffix[] = { "@163.com", "@qq.com", "@sohu.com","@google.com" };public static String generateEmail() {int prefixIndex = random.nextInt() % kEmailPrefix.length;if (prefixIndex < 0) {prefixIndex = 0;}int suffixIndex = random.nextInt() % kEmailSuffix.length;if (suffixIndex < 0)suffixIndex = 0;int number = random.nextInt() % 1000;if (number < 0) {return kEmailPrefix[prefixIndex] + kEmailSuffix[suffixIndex];} else {return kEmailPrefix[prefixIndex] + number+ kEmailSuffix[suffixIndex];}}final static StringBuffer strBuffer = new StringBuffer();public static String generateHomePhone() {strBuffer.delete(0, strBuffer.length());strBuffer.append("028");for (int i = 0; i < 8; i++) {int number = random.nextInt() % 10;if (number < 0)number = 8;strBuffer.append(number);}return strBuffer.toString();}final static String kMobilePrefix[] = { "135", "138", "139", "189", "130" };public static String generateMobilePhone() {strBuffer.delete(0, strBuffer.length());int number = random.nextInt() % kMobilePrefix.length;if (number < 0)number = 0;strBuffer.append(kMobilePrefix[number]);for (int i = 0; i < 8; i++) {number = random.nextInt() % 10;if (number < 0)number = 8;strBuffer.append(number);}return strBuffer.toString();}final static int kInsertOnceLimit = 10;/** {@inheritDoc} */@Overrideprotected Integer doInBackground(Integer... count) {final ContentResolver resolver = context.getContentResolver();int complement = count[0] % kInsertOnceLimit;EntitySet rawContactSet = null;int size = 0;for (int i = count[0]; i > 0; i = i - kInsertOnceLimit) {if (i >= kInsertOnceLimit) {rawContactSet = generateRawContactSet(kInsertOnceLimit);} elserawContactSet = generateRawContactSet(complement);rawContactSet.splitRawContacts();publishProgress((kInsertOnceLimit*100/count[0])/4);//Build operations and try applyingfinal ArrayList<ContentProviderOperation> diff = rawContactSet.buildDiff();ContentProviderResult[] results = null;if (!diff.isEmpty()) {try {results = resolver.applyBatch(ContactsContract.AUTHORITY,diff);} catch (RemoteException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (OperationApplicationException e) {// TODO Auto-generated catch blocke.printStackTrace();}}publishProgress((kInsertOnceLimit*100/count[0])/2);boolean res = refreshRawContactId(rawContactSet, diff, results);publishProgress((kInsertOnceLimit*100/count[0])/4);size = size + rawContactSet.size();Log.i(tag, "size:"+size);}return size;}protected void onProgressUpdate(Integer... progress) {mProgress.incrementProgressBy(progress[0]);}final static ArrayList<Long> rawContactIdList = new ArrayList<Long>(kInsertOnceLimit);private boolean refreshRawContactId(EntitySet entitySet,final ArrayList<ContentProviderOperation> diff,final ContentProviderResult[] results) {rawContactIdList.clear();long rawContactId;final int diffSize = diff.size();for (int i = 0; i < diffSize; i++) {ContentProviderOperation operation = diff.get(i);if (operation.getType() == ContentProviderOperation.TYPE_INSERT&& operation.getUri().getEncodedPath().contains(RawContacts.CONTENT_URI.getEncodedPath())) {rawContactId = ContentUris.parseId(results[i].uri);rawContactIdList.add(rawContactId);}}int size = entitySet.size();EntityDelta entityDelta = null;int k = 0;for (int i = 0; i < size; i++) {entityDelta = entitySet.get(i);if (entityDelta.isContactInsert())k++;}if (k != rawContactIdList.size()){Log.i(tag, "refresh rawContactId fail!");return false;}for (int i = 0; i < size; i++) {if (entityDelta.isContactInsert()){entityDelta = entitySet.get(i);rawContactId=rawContactIdList.get(i);entityDelta.getValues().put(RawContacts._ID,rawContactId);}}return true;}@Overrideprotected void onPostExecute(Integer result) {Toast.makeText(context, "insert " + result + " Contacts success!",Toast.LENGTH_SHORT).show();dialogResolver.dismissDialog(mProgress);}}
Account getAccount(){AccountManager am = AccountManager.get(this);Account[] accounts = am.getAccounts();HashSet<String> contactAccountTypes =new HashSet<String>();SyncAdapterType[] syncs = ContentResolver.getSyncAdapterTypes();for (SyncAdapterType sync : syncs) {if (ContactsContract.AUTHORITY.equals(sync.authority) &&sync.supportsUploading()) {contactAccountTypes.add(sync.accountType);}}ArrayList<Account> contactAccounts=new ArrayList<Account>();for (Account acct: accounts) {if (contactAccountTypes.contains(acct.type)) {contactAccounts.add(acct);}}if(contactAccounts.size()==0)return null;int index=random.nextInt();if(index<0)index=-index;index=index%contactAccounts.size();return contactAccounts.get(index);}
注意,这里需要在AndroidManifes.xml中添加android.permission.GET_ACCOUNTS权限
- 使用Contact数据模型来批量插入联系人(下)
- 使用Contact数据模型来批量插入联系人(上)
- Android使用Contact数据模型来批量插入联系人
- windows mobile 5.0批量删除contact联系人
- 在android中使用Provider.Contact来取得联系人的资料
- Android 批量插入联系人 分享
- Contact数据模型之EntityDelta
- Contact数据模型之ValuesDelta
- 联系人Contact类解析
- 联系人Contact类解析
- Contact数据模型之EntitySet(EntityDeltaList)
- Contact数据模型之EntitySet(EntityDeltaList)
- Android Contact数据模型之EntityDelta
- 使用sqlbulkcopy批量插入
- Andriod Contact联系人点击事件
- 使用excel批量创建android联系人
- 使用Provider与Resolver读取系统联系人并插入联系人
- kidd风的IOS日志之IOS9获取联系人信息Contact FrameWork的基本使用
- Screen — A must for SSH
- 数据结构之冒泡排序
- C#datagridview自动编号
- Activity通过bindService启动Service后Activity和Service之间的通信!
- string和exception在vc6.0中的使用
- 使用Contact数据模型来批量插入联系人(下)
- 农妇
- XML文档操作及数据库导出XML文档
- epoll_create, epoll_ctl和epoll_wait & select
- 资治通鉴,卷一百一十五,刘裕事业的第三步,消灭海贼王
- SharedPrepferences存取其他程序的总结
- 什么是FLV视频格式?FLV视频格式是什么意思?
- 桃源忆故人---词牌欣赏
- 神州数码802.1x、DCBA协议认证方案