androidnotifications

How to get an image from another app's notification?


I'm creating a notification management app and I want to get the contents of notifications which other apps show. currently I use codes like this :

statusBarNotification.getNotification().extras.getString(Notification.EXTRA_TITLE);

and this :

statusBarNotification.getNotification().extras.getString(Notification.EXTRA_TEXT);

to read the title and text of notifications. but after a few hours I couldn't find a way to get the image which comes along with the notification's text. for example a profile picture which is showed in Whatsapp's notification. I know it's not the Small or Large icons, I checked a few times.

So if anyone could help in any way, it would be much appreciated


Solution

  • I assume you use NotificationListenerService to listen to notification from other app.

    In you NotificationService class, extract icon ressource id in extra Notification.EXTRA_SMALL_ICON and access the other app package ressources to get the Drawable.

    Notification.EXTRA_PICTURE contains the large image sent in the notification :

    public class NotificationService extends NotificationListenerService {
    
        Context context;
    
        @Override
    
        public void onCreate() {
            super.onCreate();
            context = getApplicationContext();
    
        }
    
        @Override
        public void onNotificationPosted(StatusBarNotification statusBarNotification) {
    
            // a notification is posted
    
            String pack = statusBarNotification.getPackageName();
    
            Bundle extras = statusBarNotification.getNotification().extras;
    
            int iconId = extras.getInt(Notification.EXTRA_SMALL_ICON);
    
            try {
                PackageManager manager = getPackageManager();
                Resources resources = manager.getResourcesForApplication(pack);
    
                Drawable icon = resources.getDrawable(iconId);
    
            } catch (PackageManager.NameNotFoundException e) {
                e.printStackTrace();
            }
    
            if (extras.containsKey(Notification.EXTRA_PICTURE)) {
                // this bitmap contain the picture attachment
                Bitmap bmp = (Bitmap) extras.get(Notification.EXTRA_PICTURE);
            }
    
        }
    
        @Override
    
        public void onNotificationRemoved(StatusBarNotification statusBarNotification) {
            //call when notification is removed
        }
    }