您的位置:首页 > 其它

使用Contact数据模型来批量插入联系人(下)

2011-12-02 22:12 381 查看
上文接《使用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} */
@Override protected 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); //name ContentValues 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 number ContentValues 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)); //email 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"); */ //IM ContentValues 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]; else return 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} */ @Override protected 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); } else rawContactSet = generateRawContactSet(complement); rawContactSet.splitRawContacts(); publishProgress((kInsertOnceLimit*100/count[0])/4);
//Build operations and try applying final 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 block e.printStackTrace(); } catch (OperationApplicationException e) { // TODO Auto-generated catch block e.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;
}
@Override protected void onPostExecute(Integer result) { Toast.makeText(context, "insert " + result + " Contacts success!", Toast.LENGTH_SHORT).show(); dialogResolver.dismissDialog(mProgress);
}
}

另外对于Account可以采用如下的方式得到:

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权限
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息