首页 > 解决方案 > 将联系人图像添加到 MessagingStyle 通知“人员”

问题描述

我希望我的通知包含联系人的图像。我正在使用 NotificationCompat 和 MessagingStyle 确实显示联系人的聊天消息。

这在对人使用 .setIcon 时有效,但图像是方形的,所以我想使用 setUri 但它不显示图像,而是在圆圈中看到联系人的第一个首字母。

这是我用于通知的代码。

Person person = new Person.Builder()
//                .setIcon(contactIcon)
                .setName(displayName)
                .setUri(contentLookupURI)
                .setKey(contactDetail)
                .build();

NotificationCompat.MessagingStyle chatMessageStyle = new NotificationCompat.MessagingStyle(person);

NotificationCompat.MessagingStyle.Message notificationMessage = new
                NotificationCompat.MessagingStyle.Message(
                contentText,
                System.currentTimeMillis(),
                person
        );
        chatMessageStyle.addMessage(notificationMessage);

NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context, NOTIFICATION_MESSAGES_CHANNEL_ID)
                .setSmallIcon(icon) // notification icon
                .setPriority(NotificationCompat.PRIORITY_HIGH)
                .setStyle(chatMessageStyle)
                .setOnlyAlertOnce(true)
                .setContentTitle(displayName); 

.setUri对于我使用库中使用的联系人 URI来获取联系人 ID 和查找键,然后使用以下方法:

 contactLookupURI = 
 ContactsContract.Contacts.getLookupUri(contactsList.get(0).getId(), 
 contactsList.get(0).getLookupKey());

这产生了这个:content://com.android.contacts/contacts/lookup/3118r4-2F294339313F5B16.3789r5-2F294339313F5B16/6这对我来说看起来是正确的。

示例通知

我不确定 MessagingStyle 方法的这种形式有多新,因为我找不到很多与 Person 对象一起使用的示例。

标签: androidnotifications

解决方案


这是使用带有 Glide 的远程 URL 的解决方案

第 1 步:从远程 URL 获取位图

private fun getAvatarFromUrl(photoUrl: String): Bitmap? {
        return try {
            val futureTarget = Glide.with(this)
                .asBitmap()
                .load(photoUrl)
                .submit()

            futureTarget.get()
        } catch (e: Exception) {
            Timber.e(e)
            null
        }
    }

第 2 步:将位图设置为 Person.Icon

val avatar = getAvatarFromUrl(user.avatar)
val sender = Person.Builder()
     .setName(msg.from?.name)
     .setIcon(IconCompat.createWithBitmap(avatar))
     .setImportant(true)
     .build()

推荐阅读