【发布时间】:2020-09-04 10:55:12
【问题描述】:
我想使用 Kotlin 使用新的位图 bmp 作为个人资料图片来更新联系人。我找到了editing contacts 的文档,但在意图页面上找不到更改照片的字段。我发现的任何堆栈溢出解决方案都涉及更新它的奇怪方式,即使开发人员页面鼓励使用意图。更改联系人照片的最佳方法是什么?
【问题讨论】:
标签: android android-studio kotlin android-contacts
我想使用 Kotlin 使用新的位图 bmp 作为个人资料图片来更新联系人。我找到了editing contacts 的文档,但在意图页面上找不到更改照片的字段。我发现的任何堆栈溢出解决方案都涉及更新它的奇怪方式,即使开发人员页面鼓励使用意图。更改联系人照片的最佳方法是什么?
【问题讨论】:
标签: android android-studio kotlin android-contacts
首先,永远不要使用bmp,它是一个巨大的文件,你不想将bmp照片放在任何数据库中。
所以,现在要将新图片插入特定的原始联系人,并假设您手头有一些标准图片文件(jpeg/png),您可以这样做:
val rawContactPhotoUri = Uri.withAppendedPath(
ContentUris.withAppendedId(RawContacts.CONTENT_URI, yourRawContactId), // note that this must be a RAW-contact-id, not a contact-id
RawContacts.DisplayPhoto.CONTENT_DIRECTORY
) // this is the url the represents a RawContact picture
try {
val bytes = yourPictureFile.toByteArray() // get a byte array from your pic
val fd = context.contentResolver.openAssetFileDescriptor(rawContactPhotoUri, "rw")
val os = fd?.createOutputStream()
os?.write(bytes)
os?.close()
fd?.close()
} catch (e: IOException) {
// Handle the error
}
【讨论】: