Load image from url in notification Android

前端 未结 8 743
北海茫月
北海茫月 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:30

    I know a good answer has been given so let's see if we can make it easier to understand and implement.
    ---------------------Theory------------------------
    The problem can be abstracted in two step solution namely
    1) Get image from a URL
    2) Decode image and pass to notification builder

    1) Get image from a URL
    InputStream in = new URL("Img URL goes here eg. http://gg.com/profile.jpg").openStream();

    2) Decode and pass to notification
    Bitmap bmp = null; #create a null bmp container that will be used to hold decoded img
    bmp = BitmapFactory.decodeStream(in); # save the image into container

    Voila! once you build the image and save it in the variable bmp, you can call it on notification builder .setLargeIcon(bmp)

    --------Implementation---------------
    Android studio will encourage you to wrap your code with try catch so the end product will look like this.

    Bitmap bmp = null;
    try {
        InputStream in = new URL("url goes here").openStream();
        bmp = BitmapFactory.decodeStream(in);
    } catch (IOException e) {
        e.printStackTrace();
    }
    

    Once you have the bmp you can call it in notification builder as

    NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this, CHANNEL_ID)
                .setSmallIcon(R.drawable.ic_launcher)
                .setContentText("title")
                .setContentText("text goes here")
                .setLargeIcon(bmp)
                .setAutoCancel(true);
    
    0 讨论(0)
  • 2020-11-28 22:39

    Since image is loaded from internet, it should be done async in a background thread. Either use async task or Glide (for efficient image loading).

    To load image notification, you need to use "NotificationCompat.BigPictureStyle()". This requires a bitmap (which has to be extracted from image url)

    Most of the API's and methods of Glide are now deprecated. Below is working with Glide 4.9 and upto Android 10.

     // Load bitmap from image url on background thread and display image notification
            private void getBitmapAsyncAndDoWork(String imageUrl) {
    
                final Bitmap[] bitmap = {null};
    
                Glide.with(getApplicationContext())
                        .asBitmap()
                        .load(imageUrl)
                        .into(new CustomTarget<Bitmap>() {
                            @Override
                            public void onResourceReady(@NonNull Bitmap resource, @Nullable Transition<? super Bitmap> transition) {
    
                                bitmap[0] = resource;
                                // TODO Do some work: pass this bitmap
                                displayImageNotification(bitmap[0]);
                            }
    
                            @Override
                            public void onLoadCleared(@Nullable Drawable placeholder) {
                            }
                        });
            }
    

    Display the image notification once, the bitmap is ready.

    private void displayImageNotification(Bitmap bitmap) {
    
          NotificationCompat.Builder builder = new NotificationCompat.Builder(getApplicationContext(), getChannelId());
                builder
                        .setContentTitle(title)
                        .setContentText(subtext)
                        .setDefaults(Notification.DEFAULT_LIGHTS | Notification.DEFAULT_VIBRATE)
                        .setSmallIcon(SMALL_ICON)
                        .setPriority(NotificationCompat.PRIORITY_DEFAULT)
                        .setColor(getApplicationContext().getColor(color))
                        .setAutoCancel(true)
                        .setOngoing(false)
                        .setOnlyAlertOnce(true)
                        .setContentIntent(pendingIntent)
                         .setStyle(
                         new NotificationCompat.BigPictureStyle().bigPicture(bitmap))
                        .setPriority(Notification.PRIORITY_HIGH);
    
            getManager().notify(tag, id, builder.build());
    }
    
    0 讨论(0)
提交回复
热议问题