找遍了网上,都没找到批量删除手机联系人好友的方法,有也效率特别低,删除200个人都要几十秒,反而批量添加联系人速度很快
批量插入联系人
public static boolean batchAddContact(Context context, List<PhoneModel> list) {
ArrayList<ContentProviderOperation> ops = new ArrayList<>();
int rawContactInsertIndex;
if (list == null || list.size() == 0) {
return false;
}
for (int i = 0; i < list.size(); i++) {
rawContactInsertIndex = ops.size();
ops.add(ContentProviderOperation.newInsert(ContactsContract.RawContacts.CONTENT_URI)
.withValue(ContactsContract.RawContacts.ACCOUNT_TYPE, null)
.withValue(ContactsContract.RawContacts.ACCOUNT_NAME, null)
.withYieldAllowed(true)
.build());
ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
.withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID,
rawContactInsertIndex)
.withValue(ContactsContract.Data.MIMETYPE,
ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE)
.withValue(ContactsContract.CommonDataKinds.StructuredName.DISPLAY_NAME, list.get(i).getName())
.withYieldAllowed(true)
.build());
ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
.withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, rawContactInsertIndex)
.withValue(ContactsContract.Data.MIMETYPE,
ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE)
.withValue(ContactsContract.CommonDataKinds.Phone.NUMBER, list.get(i).getNumber())
.withValue(ContactsContract.CommonDataKinds.Phone.TYPE, Phone.TYPE_MOBILE)
.withYieldAllowed(true)
.build());
}
try {
//这里才调用的批量添加
context.getContentResolver().applyBatch(ContactsContract.AUTHORITY, ops);
} catch (RemoteException e) {
e.printStackTrace();
return false;
} catch (OperationApplicationException e) {
e.printStackTrace();
return false;
}
return true;
}
批量删除联系人
1、先找出每条记录的 ContractId,并存储起来
Cursor cursor = _mActivity.getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null, null, null);
while (cursor.moveToNext()) {
long contactId = cursor.getLong(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.RAW_CONTACT_ID));
String name = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
for (PhoneModel model : mDatas) {
if (model.getName().equals(name)) {
model.setContactId(contactId);
}
}
}
if (cursor != null) {
cursor.close();
}
2、然后通过这个方法,遍历删除(测试过,时间比网上的一些方法,快100倍吧)
public static void batchDelContact(Context context, List<PhoneModel> list) {
ArrayList<ContentProviderOperation> ops = new ArrayList<>();
for (int i = 0; i < list.size(); i++) {
PhoneModel model = list.get(i);
ops.add(ContentProviderOperation.newDelete(ContentUris.withAppendedId(ContactsContract.RawContacts.CONTENT_URI, model.getContactId()))
.withYieldAllowed(true)
.build());
}
try {
context.getContentResolver().applyBatch(ContactsContract.AUTHORITY, ops);
} catch (OperationApplicationException e) {
e.printStackTrace();
} catch (RemoteException e) {
e.printStackTrace();
}
}