Android - use external profile image in notification bar like Facebook

后端 未结 5 1483
眼角桃花
眼角桃花 2020-11-30 06:37

I know you can send info in the push notification parameters like message, title, image URL, etc. How does Facebook show your profile pic with your message in the notificati

5条回答
  •  -上瘾入骨i
    2020-11-30 07:14

    Since image is loaded from internet, it should be done async in a background thread.You can use (1) async task or (2) 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.

    Step 1: Load bitmap from image url on background thread

       private void getBitmapAsyncAndDoWork(String imageUrl) {
    
                final Bitmap[] bitmap = {null};
    
                Glide.with(getApplicationContext())
                        .asBitmap()
                        .load(imageUrl)
                        .into(new CustomTarget() {
                            @Override
                            public void onResourceReady(@NonNull Bitmap resource, @Nullable Transition transition) {
    
                                bitmap[0] = resource;
                                // TODO Do some work: Load image notification from here
                                displayImageNotification(bitmap[0]);
                            }
    
                            @Override
                            public void onLoadCleared(@Nullable Drawable placeholder) {
                            }
                        });
            }
    

    Step 2: 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());
    }
    

提交回复
热议问题