Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NotificationListenerService get Notification Icon?

In a Service extending the new (SDK18, JB-4.3) NotificationListenerService, I'd like to get the Notification's status bar icon.

mStatusBarNotification.getNotification().icon returns the resource id of the status bar drawable, but that resource id is naturally not within my app's scope/resources. There's also mStatusBarNotification.getNotification().largeIcon (returning a Bitmap), but that's not set for all notifications and returns the "wrong" icon (the image in the expanded notification drawer).

like image 299
Nick Avatar asked Mar 23 '23 22:03

Nick


2 Answers

Use getPackageName() on StatusBarNotification to find out the app that posted the Notification. You can then use createPackageContext() to get a Context for that package, then use that Context to retrieve the image (e.g., via getResources()).

like image 63
CommonsWare Avatar answered Mar 29 '23 23:03

CommonsWare


This is the alternative workaround.

We can get drawable from sbn.getNotification().extras.getInt("android.icon") and then use customview to show this drawable in the notification.

This is how to get Drawable using android.icon value:

            RemoteViews contentView = new RemoteViews(context.getPackageName(), R.layout.custom_push_notification);
            contentView.setImageViewResource(R.id.image, R.mipmap.ic_launcher);
            contentView.setTextViewText(R.id.title, notificationModel.getTitle());
            contentView.setTextViewText(R.id.text, notificationModel.getBody());
           

            try {
                   //now get the context of other app and then get drawable from resoures
                    Drawable drawable1 = context.createPackageContext(notificationModel.getPackageName(), CONTEXT_IGNORE_SECURITY).getDrawable(notificationModel.getIcon());
                    Bitmap bitmap = drawableToBitmap(drawable1);
                    contentView.setImageViewBitmap(R.id.image, bitmap);
            } catch (PackageManager.NameNotFoundException e) {
                e.printStackTrace();
            }

My notificationModel is:

notificationModel.setKey(sbn.getId());
like image 31
Nouman Ch Avatar answered Mar 30 '23 01:03

Nouman Ch