【问题标题】:Android Messaging Style notification -Add icon from image URL - Person.BuilderAndroid 消息传递样式通知 - 从图像 URL 添加图标 - Person.Builder
【发布时间】:2022-11-25 07:45:03
【问题描述】:

我正在使用 Person 对象来构建聊天应用程序通知,例如 Gmail。所以我创建了人对象。但我想从来自服务器而不是可绘制资源的图像 URL 设置图标。我正在使用 Coil 库加载图像。下面的代码工作正常,

默认情况下,android 会生成带有传递给标题的第一个字母的图标。 那么,我如何将来自服务器的图像显示为图标中的 URL 以及内存和资源使用的最佳实践。下面是我的 Person 对象。 这是Person的官方链接。 这就是我所说的Notification Messaging style tutorial

    val senderPerson: Person = Person.Builder().also {person->
        person.setKey(message.getSenderKey(prefs))
        person.setName(message.getNotificationTitle())
        person.setImportant(true)
//****HERE I WANT TO SET IMAGE FROM URL******
        //    person.setIcon(IconCompat.createWithResource(this, R.drawable.placeholder_transaparent))
    }.build()

【问题讨论】:

    标签: android kotlin notifications kotlin-coroutines coil


    【解决方案1】:

    您将使用 Coil Request 异步加载图像 URL,并在闭包中返回获取的图标。

    Coil 返回一个可绘制对象,您可以使用 IconCompat.createWithBitmap((drawable as BitmapDrawable).bitmap) 通过位图从 Drawable 获取图标:

    private fun asyncLoadIcon(imageUrl: String?, setIcon: (IconCompat?) -> Unit) {
        if (imageUrl.isNullOrEmpty())
            setIcon(null)
        else {
            // using COIL to load the image
            val request = ImageRequest.Builder(this)
                .data(imageUrl)
                .target { drawable ->
                    setIcon(IconCompat.createWithBitmap((drawable as BitmapDrawable).bitmap)) //  // Return the fetched icon from the URL
                }
                .listener(object : ImageRequest.Listener { // Return null icon if the URL is wrong
                    override fun onError(request: ImageRequest, result: ErrorResult) {
                        setIcon(null)
                    }
                })
                .build()
            imageLoader.enqueue(request)
        }
    }
    

    如果 URL 错误或为空/空,此代码将返回一个空图标。

    然后使用该函数构建通知消息:

    asyncLoadIcon("https://my_icon_url.png") { // set the icon url
    
        val person = Person.Builder().apply {
            setName("John Doe")
            setIcon(it)
        }.build()
        
        // Build the notification with the person
        .....
        
    }
    

    对于某些增强功能,您将启用缓存并禁用硬件位图;但我确实推荐其他库,如 Glide 和 Picasso。

    .memoryCachePolicy(CachePolicy.ENABLED)
    .diskCachePolicy(CachePolicy.ENABLED)
    .allowHardware(false) // Disable hardware bitmaps
    

    【讨论】:

      猜你喜欢
      • 2021-12-19
      • 2017-09-04
      • 1970-01-01
      • 2014-09-10
      • 2023-04-01
      • 2016-09-16
      • 1970-01-01
      相关资源
      最近更新 更多