Android 从NotificationListenerService在数据库中存储通知小图标

Android 从NotificationListenerService在数据库中存储通知小图标,android,android-notifications,Android,Android Notifications,我有一个NotificationListenerService,它拦截所有传入的通知,并将信息记录在SQLite数据库中。我遇到的唯一问题是如何获取状态栏图标,也就是小图标 notification.icon自API 23以来已被弃用,而extras.getInt(notification.EXTRA\u SMALL\u icon)自API 26以来已被弃用 在Android10(API 29)之前,extras.getInt(“Android.icon”)工作得很好,但现在每个通知都返回0,尽

我有一个NotificationListenerService,它拦截所有传入的通知,并将信息记录在SQLite数据库中。我遇到的唯一问题是如何获取状态栏图标,也就是小图标

notification.icon
自API 23以来已被弃用,而
extras.getInt(notification.EXTRA\u SMALL\u icon)
自API 26以来已被弃用

在Android10(API 29)之前,
extras.getInt(“Android.icon”)
工作得很好,但现在每个通知都返回0,尽管有趣的是(据我所知)它与
extras.getInt(notification.EXTRA\u SMALL\u icon)
相同

我知道现在建议使用
getSmallIcon()
,但如何将其存储在数据库中?在过去,我能够从上述方法获取资源id,但是
getSmallIcon()
返回一个Icon对象。我知道我可以将其转换为可绘制的或位图,但如何获取不知道其名称的对象的资源id?尽管如此,还是来自另一个应用程序

注意:我知道有一个
getSmallIcon()
方法叫做
getResId()
,但是这个调用需要API 28,这个API比我希望的最低API要高


我这样做对吗?有没有我找不到的更好的方法来实现这一点?

我为将来发现这一点的人想出了一个解决方案:

int iconResId = 0;

// if the API is P or above, this is easy
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
    iconResId = notificationSmallIcon.getResId();
}

// in case the getResId doesn't work, or the API is below P
if (iconResId == 0) {

    /* first try to get it from the small icon
        if the icon is from a resource, then the toString() method will contain the resource id, 
        but masked to a hex value, so we need to get it back to its integer value
     */
    final String smallIconString = notificationSmallIcon.toString();
    if (smallIconString.contains("id=")) {
        final String iconHexId = smallIconString.substring(smallIconString.indexOf("id=") + 5).replace(")", "");
        iconResId = Integer.parseInt(iconHexId, 16);
    }

    /* if still zero, above method didn't work, use the deprecated method as I've found it to still
        be reliable despite it, you know, being deprecated since API 23
     */
    if (iconResId == 0) {
        iconResId = notification.icon;
    }

}

// if still zero now, either there's no icon, or none of the above methods work anymore