Load image from url in notification Android

前端 未结 8 839
北海茫月
北海茫月 2020-11-28 21:48

In my android application, i want to set Notification icons dynamically which will be loaded from URL. For that, i have used setLargeIcon property of Notificati

8条回答
  •  孤街浪徒
    2020-11-28 22:25

    Top answer in Kotlin and with Coroutines. This method applies the bitmap to the builder instead of a direct assignment, and of course if bitmap available. It's nice because if the url is wrong it will be caught in the try/catch.

    fun applyImageUrl(
        builder: NotificationCompat.Builder, 
        imageUrl: String
    ) = runBlocking {
        val url = URL(imageUrl)
    
        withContext(Dispatchers.IO) {
            try {
                val input = url.openStream()
                BitmapFactory.decodeStream(input)
            } catch (e: IOException) {
                null
            }
        }?.let { bitmap ->
            builder.setLargeIcon(bitmap)
        }
    }
    

    with Kotlin & RxJava

    fun applyImageUrl(
        builder: NotificationCompat.Builder,
        imageUrl: String
    ) {
        val url = URL(imageUrl)
    
        Single.create { emitter ->
            try {
                val input = url.openStream()
                val bitmap = BitmapFactory.decodeStream(input)
                emitter.onSuccess(bitmap)
            } catch (e: Exception) {
                emitter.onError(e)
            }
        }.subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(
                {
                    builder.setLargeIcon(it)
                }, {
                    Timber.e("error generating bitmap for notification")
                }
            )
    }
    

提交回复
热议问题