通知监听服务如何获取通知图标?

4
在扩展新的(SDK18,JB-4.3)NotificationListenerService中,我想获取通知状态栏图标。mStatusBarNotification.getNotification().icon返回状态栏可绘制资源的资源ID,但该资源ID自然不在我的应用程序范围/资源内。还有mStatusBarNotification.getNotification().largeIcon(返回Bitmap),但并非针对所有通知设置,并且返回“错误”的图标(扩展通知抽屉中的图像)。
2个回答

6

使用 getPackageName() 方法获取 StatusBarNotification 对象中的通知所属应用程序的包名。然后,您可以使用createPackageContext() 方法获取该包名所对应的 Context 对象,进而使用该 Context 对象访问应用程序资源(例如通过 getResources() 方法来获取图像)。


这是怎么工作的?setSmallIcon仍然需要一个int资源ID,而使用createPackageContext和getResources只会让我访问Drawable本身。 - Kyle Jahnke
@KyleJahnke: 我不知道是否有一个setSmallIcon()方法与这个问题有任何关系。也许你想要创建一个Notification; 这个问题不是关于创建Notification,而是检查现有的Notification - CommonsWare
4
他在询问如何找到其他通知所输入的图标,以便在setSmallIcon()中使用。notification.extras.getInt(Notification.EXTRA_SMALL_ICON) - Dave Lugg
@CommonsWare 这并没有提供一个合适的答案。 - Nouman Ch
@NoumanCh:你在回答中使用了我提供的技巧(createPackageContext())。 - CommonsWare
显示剩余3条评论

1
这是另一种替代方法。
我们可以从sbn.getNotification().extras.getInt("android.icon")获取可绘制对象,然后使用自定义视图在通知中显示该可绘制对象。
以下是使用 android.icon 值获取 Drawable 的方法:
            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();
            }

我的notificationModel是:

notificationModel.setKey(sbn.getId());

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接