首页 > 代码库 > 通过 ContentResolver 读取联系人信息

通过 ContentResolver 读取联系人信息

1、首先动态获取 读取联系人信息权限
   <1>配置文件中声明对应权限
<uses-permission android:name="android.permission.READ_CONTACTS"/>
   <2>判断是否具有对应权限
     if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_CONTACTS) !=
PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, arrayOf(Manifest.permission.READ_CONTACTS), 1)
} else {
readContacts() //读取联系人信息
}
  <3>授权
   override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
when (requestCode) {
1 ->
if (grantResults.size > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
readContacts()
} else {
Toast.makeText(this, "You denied the permission", Toast.LENGTH_SHORT).show()
}
}
}

2、创建ListView适配器,联系人信息集合
  var adapter: ArrayAdapter<String>? = null
var contactsList = mutableListOf<String>()
   //实例化 适配器
adapter = ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, contactsList)
//listView 设置适配器
lv_contents_view.adapter = adapter
3、读取联系人信息
    /**
* 加载联系人信息
*/
private fun readContacts() {
var cursor: Cursor

//查询联系人数据
cursor = contentResolver.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
null, null, null, null)
if (cursor != null) {
while (cursor.moveToNext()) {
//获取联系人姓名
var displayName = cursor.getString(cursor.getColumnIndex(
ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME))
//获取联系人电话
var number = cursor.getString(cursor.getColumnIndex(
ContactsContract.CommonDataKinds.Phone.NUMBER))
// 添加联系人信息到集合当中
contactsList.add(displayName + "\n" + number)
}
//刷新 ListView
adapter?.notifyDataSetChanged()
}
cursor.close() //关闭 Cursor 对象
}

4、成功显示数据
技术分享

注意:编程所用语言为 Kotlin


null


通过 ContentResolver 读取联系人信息