9

How to use Glide into NotificationCompat.Builder setLargeIcon(Bitmap icon)? I already looked into this tutorial but I don't want to use RemoteViews. I also want to get use of Glide.placeholder(int resource) and Glide.error(int resource) without using the strategy Glide.into(new SimpleTarget<Bitmap>(){ ... });

Zoe
  • 27,060
  • 21
  • 118
  • 148
Damia Fuentes
  • 5,308
  • 6
  • 33
  • 65

2 Answers2

7

here is how I did this with Glide 4.8.0

val notificationBuilder = NotificationCompat.Builder(this, channelId)
            .setSmallIcon(R.drawable.ic_message)
            .setContentTitle("title")
            .setContentText("text")

val notificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager

val futureTarget = Glide.with(this)
            .asBitmap()
            .load(photoUrl)
            .submit()
    
val bitmap =
        try {
            futureTarget.get()
        }
        catch (e: InterruptedException) {
            //set bitmap fallback in case of glide get fail on a 404 response
        }
        catch (e: ExecutionException) {
            //set bitmap fallback in case of glide get fail on a 404 response
        }

notificationBuilder.setLargeIcon(bitmap)

Glide.with(this).clear(futureTarget)

notificationManager.notify(0, notificationBuilder.build())

result:

enter image description here

Mr.Drew
  • 939
  • 2
  • 9
  • 30
Dan Alboteanu
  • 9,404
  • 1
  • 52
  • 40
2

Finally I did not find a way to this so I did the strategy Glide.into(new SimpleTarget<Bitmap>(){ ... });, which is:

int largeIconSize = Math.round(64 * context.getResources().getDisplayMetrics().density);
GlideApp.with(context)
        .asBitmap()
        .load(largeIconUrl)
        .override(largeIconSize, largeIconSize)
        .placeholder(placeHolderResource)
        .into(new BaseTarget<Bitmap>() {
            @Override
            public void onResourceReady(Bitmap resource, Transition<? super Bitmap> transition) {
                notificationBuilder.setLargeIcon(resource);
                publish();
            }

            @Override
            public void getSize(SizeReadyCallback cb) {
                cb.onSizeReady(largeIconSize, largeIconSize);
            }

            @Override
            public void onLoadFailed(@Nullable Drawable errorDrawable) {
                super.onLoadFailed(errorDrawable);
                notificationBuilder.setLargeIcon(((BitmapDrawable) errorDrawable).getBitmap());
                publish();
            }

            @Override
            public void onLoadStarted(@Nullable Drawable placeholder) {
                super.onLoadStarted(placeholder);
                notificationBuilder.setLargeIcon(((BitmapDrawable) placeholder).getBitmap());
                publish();
            }
        });

and publish() is:

Notification notification = notificationBuilder.build();
notificationManager.notify(notificationID, notification);
Damia Fuentes
  • 5,308
  • 6
  • 33
  • 65