插入联系人优化

时间:2013-01-29 16:23:01

标签: java android contacts

我使用此代码填充我的联系人,但添加一个联系人需要很长时间(约400milis)。我能以某种方式优化插入吗?出于测试目的,我需要填充大约5000个联系人,这可能需要很长时间才能完成。

public void addContact(ArrayList<String> info){
    byte[] imageToLoad;
    ArrayList<ContentProviderOperation> op_list = new ArrayList<ContentProviderOperation>(); 
    op_list.add(ContentProviderOperation.newInsert(ContactsContract.RawContacts.CONTENT_URI) 
        .withValue(ContactsContract.RawContacts.ACCOUNT_TYPE, null) 
        .withValue(ContactsContract.RawContacts.ACCOUNT_NAME, null) 
        //.withValue(RawContacts.AGGREGATION_MODE, RawContacts.AGGREGATION_MODE_DEFAULT) 
        .build()); 

 // first and last names 
      op_list.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI) 
  .withValueBackReference(Data.RAW_CONTACT_ID, 0) 
        .withValue(Data.MIMETYPE, StructuredName.CONTENT_ITEM_TYPE) 
        .withValue(StructuredName.GIVEN_NAME, info.get(0)) 
        .withValue(StructuredName.FAMILY_NAME, info.get(1)) 
        .build()); 

      op_list.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI) 
              .withValueBackReference(Data.RAW_CONTACT_ID, 0) 
              .withValue(ContactsContract.Data.MIMETYPE,ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE)
              .withValue(ContactsContract.CommonDataKinds.Phone.NUMBER, info.get(2))
              .withValue(ContactsContract.CommonDataKinds.Phone.TYPE, Phone.TYPE_CUSTOM)
              .build());
      op_list.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI) 
              .withValueBackReference(Data.RAW_CONTACT_ID, 0)

      .withValue(ContactsContract.Data.MIMETYPE,ContactsContract.CommonDataKinds.Email.CONTENT_ITEM_TYPE)
      .withValue(ContactsContract.CommonDataKinds.Email.DATA, info.get(3))
      .withValue(ContactsContract.CommonDataKinds.Email.TYPE, "emailType")
      .build());



      switch (info.get(4).charAt(0)) {
    case '1':
        imageToLoad = image1;
        break;
    case '2':
        imageToLoad = image2;
        break;
    case '3':
        imageToLoad = image3;
        break;
    default:
        imageToLoad = null;
        break;
    }


      Log.e("ContactGenerator", info.get(0) + "   "+ info.get(1) + "   " + info.get(2) + "   " +info.get(3) );


      op_list.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
      .withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, 0)
      .withValue(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.Photo.CONTENT_ITEM_TYPE)
      .withValue(ContactsContract.CommonDataKinds.Photo.PHOTO, imageToLoad)
      .build());

      info = null;

 try{ 
  ContentProviderResult[] results = getContentResolver().applyBatch(ContactsContract.AUTHORITY, op_list); 
 }catch(Exception e){ 
  e.printStackTrace(); 
 } 
}

0 个答案:

没有答案