我有一个应用程序,使用下面的代码在电话簿中插入/更新联系人,该代码可以工作,但是我面临的问题是,例如,具有相同电话号码的相似联系人。 WhatsApp,dou,Viber等联系人,然后这些应用程序联系人接管了我的联系人DisplayName并合并在一起,但是由于这个原因,我们在某些版本的android(如Samsung,LG,MI A5 stock android)等中存在多个重复项。
但是可以在某些手机上使用,例如MI Max和其他一些手机,有人能解决此问题吗?或者我是否缺少某些字段,所以需要避免重复联系人。
private fun insertContact(contact: Contact): Boolean {
try {
val operations = ArrayList<ContentProviderOperation>()
ContentProviderOperation.newInsert(RawContacts.CONTENT_URI).apply {
withValue(RawContacts.accOUNT_NAME,"abcd@gmail.com")
withValue(RawContacts.accOUNT_TYPE,"google.com")
operations.add(build())
}
ContentProviderOperation.newInsert(Data.CONTENT_URI).apply {
withValueBackReference(Data.RAW_CONTact_ID,0)
withValue(Data.MIMETYPE,StructuredName.CONTENT_ITEM_TYPE)
withValue(StructuredName.GIVEN_NAME,contact.firstName)
withValue(StructuredName.FAMILY_NAME,contact.lastName)
withValue(StructuredName.SUFFIX,"AppName")
operations.add(build())
}
addUpdatePhone(operations,contact.phoneNumbers)
//similar function for other fields email,address,birthday,profilePic etc
val results = context.contentResolver.applyBatch(ContactsContract.AUTHORITY,operations)
return true
} catch (e: Exception) {
LOG.e( "Error inserting contact")
return false
}
}
private fun updateContact(contact: contact,rawContactId: String): Boolean {
try {
val operations = ArrayList<ContentProviderOperation>()
ContentProviderOperation.newUpdate(Data.CONTENT_URI).apply {
val selection = "${Data.RAW_CONTact_ID} = ? AND ${Data.MIMETYPE} = ?"
val selectionArgs = arrayOf(rawContactId,StructuredName.CONTENT_ITEM_TYPE)
withSelection(selection,selectionArgs)
withValue(StructuredName.GIVEN_NAME,contact.phoneNumbers,true,rawContactId)
//similar function for other fields email,profilePic etc
context.contentResolver.applyBatch(ContactsContract.AUTHORITY,operations)
return true
} catch (e: Exception) {
LOG.e("Error updating contact")
return false
}
}
private fun addUpdatePhone(operations: ArrayList<ContentProviderOperation>,phoneNumbers: List<PhoneNumber>,isUpdate: Boolean = false,rawContactId: String = "") {
if(isUpdate) {
//delete old data with the given raw_contact_id
ContentProviderOperation.newDelete(Data.CONTENT_URI).apply {
val selection = "${Data.RAW_CONTact_ID} = ? AND ${Data.MIMETYPE} = ? "
val selectionArgs = arrayOf(rawContactId,Phone.CONTENT_ITEM_TYPE)
withSelection(selection,selectionArgs)
operations.add(build())
}
}
phoneNumbers.forEach {
//add new rows of phone number for the given raw_contact_id
ContentProviderOperation.newInsert(Data.CONTENT_URI).apply {
if(isUpdate) {
withValue(Data.RAW_CONTact_ID,rawContactId)
} else {
withValueBackReference(Data.RAW_CONTact_ID,0)
}
withValue(Data.MIMETYPE,Phone.CONTENT_ITEM_TYPE)
withValue(Phone.TYPE,it.type)
withValue(Phone.LABEL,it.label)
withValue(Phone.NUMber,it.value)
withValue(Phone.NORMALIZED_NUMber,it.value.normalizeNumber())
operations.add(build())
}
}
}
//similar functions as above for other fields
private fun otherupdateFunAsAbove() {}