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

Store Notification Small Icon in Database from NotificationListenerService

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

notification.icon 自 API 23 起已弃用,extras.getInt(Notification.EXTRA_SMALL_ICON) 自 API 26 起已弃用。

直到 Android 10 (API 29),extras.getInt("android.icon") 工作正常,但现在 returns 0 对于每个通知,尽管它很有趣(到目前为止据我所知)与 extras.getInt(Notification.EXTRA_SMALL_ICON).

相同

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

注意:我知道有一个 getSmallIcon() 的方法叫做 getResId(),但是这个调用需要 API 28,比我想要的高 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