如何从其他应用的通知中获取图片?

时间:2016-10-30 01:39:49

标签: android notifications

我正在创建通知管理应用,我想获取其他应用显示的通知内容。目前我使用这样的代码:

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

和此:

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

阅读通知的标题和文字。但几个小时后,我无法找到一种方法来获取与通知文本一起出现的图像。例如,在Whatsapp的通知中显示的个人资料图片。我知道它不是小图标或大图标,我检查过几次。

因此,如果有人能以任何方式提供帮助,我们将不胜感激

1 个答案:

答案 0 :(得分:3)

我假设您使用NotificationListenerService收听来自其他应用的通知。

NotificationService课程中,在额外Notification.EXTRA_SMALL_ICON中提取图标资源ID并访问其他应用包资源以获取Drawable

Notification.EXTRA_PICTURE包含通知中发送的大图片:

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
    }
}