这只是一个很好的实现(在 Kotlin 中),我将在此处添加它以帮助从光标获取联系信息。您还需要授予权限并请求运行时权限
<uses-permission android:name="android.permission.READ_CONTACTS" />
@SuppressLint("Recycle")
private fun getContactDataFrom(
contentResolver: ContentResolver,
contactUri: Uri
): ContactModel? {
val projection = arrayOf(
ContactsContract.Contacts._ID,
ContactsContract.Contacts.DISPLAY_NAME,
ContactsContract.Contacts.HAS_PHONE_NUMBER
)
try {
val cursor = contentResolver.query(contactUri, projection, null, null, null) ?: return null
if (!cursor.moveToFirst()) {
return null
}
val id = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID))
val name = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME))
val hasNumber = (cursor.getInt(cursor.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER)))
cursor.close()
val email = getEmail(contentResolver, id)
val phoneNumber = if (hasNumber > 0) {
getPhoneNumber(contentResolver, id)
} else {
""
}
return ContactModel(name, phoneNumber, email)
} catch (e: Exception) {
Log.e("Contacts", "Could not get contact info.", e)
return null
}
}
@SuppressLint("Recycle")
private fun getPhoneNumber(contentResolver: ContentResolver, id: String?): String {
var phoneNumber = ""
val cursor = contentResolver.query(
ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
null,
ContactsContract.Contacts._ID + " = ?",
arrayOf(id),
null
) ?: return phoneNumber
if (cursor.moveToFirst()) {
phoneNumber = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DATA))
}
cursor.close()
return phoneNumber
}
@SuppressLint("Recycle")
private fun getEmail(contentResolver: ContentResolver, id: String?): String {
var email = ""
val cursor = contentResolver.query(
ContactsContract.CommonDataKinds.Email.CONTENT_URI,
null,
ContactsContract.CommonDataKinds.Email.CONTACT_ID + " = ?",
arrayOf(id),
null
) ?: return email
if (cursor.moveToFirst()) {
email = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA))
}
cursor.close()
return email
}
扳机:
val intent = Intent(this, PickLabelActivity::class.java)
startActivityForResult(intent, PickLabelActivity.REQ_CODE_PICK_LABEL)
onActivityResult 中的用法应该类似于:
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if (resultCode == RESULT_OK && requestCode == ConstantsHandler.INTENT_CODE_PICK_CONTACT) {
val contactUri = data?.data ?: return
val contactModel = getContactDataFrom(contentResolver, contactUri)
inputName.setText(contactModel?.name)
inputPhone.setText(contactModel?.phone)
inputEmail.setText(contactModel?.email)
}
}
而那个 ContactModel 只是一个简单的数据类。
data class ContactModel(
var name: String? = null,
var phone: String? = null,
var email: String? = null
) : Serializable