跳转联系人页面,选取联系人之后,返回联系人姓名以及联系人电话,没有电话号吗的不会返回,一个联系人有多个电话号码时会分多个返回
//跳转联系人Intent
var intent = Intent(Intent.ACTION_PICK, ContactsContract.CommonDataKinds.Phone.CONTENT_URI)
获取到联系人uri之后,通过contentResolver查询联系人姓名以及电话
val contactUri = result.data?.data
contactUri?.let {
contentResolver.query(contactUri, null, null, null, null).use { cursor ->
if (cursor?.moveToFirst() == true) {
var number = ""
var name = ""
val numberIndex =
cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER)
if (numberIndex != -1) {
number = cursor.getString(numberIndex)
if (number.isNotEmpty()) {
binding.etPhone.setText(number.replace(" ", ""))
}
}
val nameIndex =
cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME)
if (nameIndex != -1) {
name = cursor.getString(nameIndex)
}
Log.e("TAG", "$name:$number")
}
}
}
完整代码:
registerForActivityResult(
ActivityResultContracts.StartActivityForResult(), activityResultRegistry
) { result ->
val contactUri = result.data?.data
contactUri?.let {
contentResolver.query(contactUri, null, null, null, null).use { cursor ->
if (cursor?.moveToFirst() == true) {
var number = ""
var name = ""
val numberIndex =
cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER)
if (numberIndex != -1) {
number = cursor.getString(numberIndex)
if (number.isNotEmpty()) {
binding.etPhone.setText(number.replace(" ", ""))
}
}
val nameIndex =
cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME)
if (nameIndex != -1) {
name = cursor.getString(nameIndex)
}
Log.e("TAG", "$name:$number")
}
}
}
}.launch(Intent(Intent.ACTION_PICK, ContactsContract.CommonDataKinds.Phone.CONTENT_URI))
网友评论