【问题标题】:Store Notification Small Icon in Database from NotificationListenerService从 NotificationListenerService 在数据库中存储通知小图标
【发布时间】:2020-02-26 02:02:56
【问题描述】:

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

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

在 Android 10 (API 29) 之前,extras.getInt("android.icon") 工作正常,但现在每个通知都返回 0,尽管有趣的是(据我所知)它与 extras.getInt(Notification.EXTRA_SMALL_ICON) 相同。

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

注意:我知道 getSmallIcon() 有一个名为 getResId() 的方法,但该调用需要 API 28,这个 API 比我希望的最低要求更高。

我这样做对吗?有没有我找不到的更好的方法?

【问题讨论】:

    标签: android android-notifications


    【解决方案1】:

    我为将来发现此问题的任何人想出了一个解决方案:

    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
    

    【讨论】:

      猜你喜欢
      • 2013-08-05
      • 2016-06-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-06-08
      相关资源
      最近更新 更多