Android 获取通讯录列表信息

345 阅读1分钟

直接上干货 kotlin语言

工具类

object ContactTools {

    private var contactsTotalList: List<SelectPerson>? = null

    private var sortedByNameList: List<SelectPerson>? = null

    /**

     * 根据名称排序后的通讯录

     */

    suspend fun getSortUserList(): List<SelectPerson> {

        if (sortedByNameList == null) {

            val list = getUserList()

            //拿到列表先排序

            val contactList = list.sortedBy { it.allName() }

            contactList.forEachIndexed { index, contactInfo ->

                val prev = contactList.getOrNull(index - 1)

                if (prev?.groupName() == contactInfo.groupName()) {//前一个和当前的字母相等

                    contactInfo.itemType = SelectPerson.CONTACT_CONTENT

                } else {//前一个和当前的字母不相等

                    //则当前的为新字母的第一个

                    contactInfo.itemType = SelectPerson.CONTACT_HEADER

                }

            }

            sortedByNameList = contactList

            return contactList

        } else return sortedByNameList!!

    }



    /**

     * 获取手机通讯录信息,务必子线程调用

     * @return List<ContactBean>

     */

    private suspend fun getUserList(): List<SelectPerson> = withContext(Dispatchers.IO) {

        if (contactsTotalList != null) return@withContext contactsTotalList!!

        val contacts = mutableListOf<SelectPerson>()

        val cursor = appContext.contentResolver.catchQuery {

            query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null)

        }

        cursor?.foreachUse {

            val idIndex = getColumnIndex(ContactsContract.Contacts._ID)

            val id = getStringOrNull(idIndex) ?: return@foreachUse

            val giveNameIndex = cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME)

            val giveName = cursor.getStringOrNull(giveNameIndex)


            getPhoneNumber(id)?.let { phone ->

                val info = SelectPerson(

                    firstName = giveName ?: "",

                    lastName = "",

                    phone = phone,

                )

                contacts.add(info)

            }

        }

        return@withContext contacts.also { contactsTotalList = it }

    }



    /**

     * 根据id获取手机号

     */

    private fun getPhoneNumber(id: String): String? {

        val phoneCursor = runCatching {

            appContext.contentResolver.query(

                ContactsContract.CommonDataKinds.Phone.CONTENT_URI,

                null,

                ContactsContract.CommonDataKinds.Phone.CONTACT_ID + "=" + id,

                null,

                null

            )

        }.onFailure { LogUtil.e(it) }.getOrNull()

        phoneCursor?.use { cursor ->

            while (cursor.moveToNext()) {

                runCatching {

                    val phoneIndex =

                        cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER)

                    val originPhone = cursor.getStringOrNull(phoneIndex)

                    return originPhone?.let {

                        originPhone.replace("-", "").replace(" ", "")

                    }

                }.onFailure {

                    LogUtil.e(it)

                }

            }

        }

        return null

    }



    fun ContentResolver.catchQuery(block: ContentResolver.() -> Cursor?): Cursor? {

        return runCatching {

            block(this)

        }.onFailure { LogUtil.e(it) }.getOrNull()

    }



    fun Cursor.foreachUse(block: Cursor.() -> Unit) {

        use {

            try {

                while (moveToNext()) {

                    runCatching { block(this) }.onFailure { LogUtil.e(it) }

                }

            } catch (t: Throwable) {

                LogUtil.e(t)

            } finally {

                it.close()

            }

        }

    }

}

选择的通讯录实体对象

data class SelectPerson(
 var    firstName = "",
 var lastName = "",
var phone = "",
)