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
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")
}
)
}