美文网首页
Android选取联系人获取电话和姓名

Android选取联系人获取电话和姓名

作者: 牛皮李哥 | 来源:发表于2021-11-29 14:49 被阅读0次

    跳转联系人页面,选取联系人之后,返回联系人姓名以及联系人电话,没有电话号吗的不会返回,一个联系人有多个电话号码时会分多个返回

    //跳转联系人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))
    

    相关文章

      网友评论

          本文标题:Android选取联系人获取电话和姓名

          本文链接:https://www.haomeiwen.com/subject/ccqlxrtx.html