首先,创建一个用于存储联系人数据的模型类:
并在您的联系人中添加 getAllContact(context) 方法:
不要忘记在清单中添加读取联系人的用户权限:
data class ContactModel(
var name: String? = "",
var mobileNumber: String? = "",
var photoURI: Uri? = null
)
class ContactsFragment : Fragment(R.layout.contacts_fragment) {
private var _binding: ContactsFragmentBinding? = null
private val binding get() = _binding
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
_binding = ContactsFragmentBinding.inflate(inflater, container, false)
return binding?.root
}
@SuppressLint("Recycle")
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
if (!context?.let { checkIfAlreadyHavePermission(it) }!!) {
context?.let { requestContactPermission(it) }
} else {
lifecycleScope.launch(Dispatchers.IO) {
context?.let { getAllContacts(it) }
Log.e("con", "con" + getAllContacts(requireContext()))
}
}
}
fun getAllContacts(context: Context): List<ContactModel> {
val contactList: ArrayList<ContactModel> = ArrayList()
val contentResolver = context.contentResolver
val notifier: Cursor? = contentResolver.query(ContactsContract.Contacts.CONTENT_URI, null, null, null, ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME + " ASC")
if (notifier!!.count > 0) {
while (notifier.moveToNext()) {
val id = notifier.getString(notifier.getColumnIndex(ContactsContract.Contacts._ID))
if (notifier.getInt(notifier.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER)) > 0)
{ val notifierInfo: Cursor? = contentResolver.query(
ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ?", arrayOf(id), null
)
val user: Uri =
ContentUris.withAppendedId(
ContactsContract.Contacts.CONTENT_URI,
id.toLong()
)
val userURI: Uri = Uri.withAppendedPath(
user,
ContactsContract.Contacts.Photo.CONTENT_DIRECTORY
)
while (notifierInfo!!.moveToNext()) {
val info = ContactModel()
info.name =
(notifier.getString(notifier.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME)))
info.mobileNumber = (
notifierInfo.getString(
notifierInfo.getColumnIndex(
ContactsContract.CommonDataKinds.Phone.NUMBER
)
)
)
contactList.add(info)
}
notifierInfo.close()
}
}
notifier.close()
}
return contactList
}