如何访问NotificationListenerService接收到的系统通知优先级?

问题描述 投票:0回答:1

我正在使用 Kotlin 为电视开发 Android 应用程序。 我创建了一个屏幕来显示从系统收到的通知。 为了获取数据,我正在使用 NotificationListenerService,我在其中收到带有 StatusBarNotification 对象的 activeNotifications 列表。

我正在尝试访问通知级别。 Android TV 支持以下通知级别:

  1. 低。只有在主屏幕上单击通知列表才能看到。
  2. 默认。当用户导航回主屏幕时,直接在主屏幕上可见的通知叠加层。
  3. 高。通知叠加层立即可见,无论用户身在何处。
  4. 关键。 Toast 立即可见,无论用户身在何处。用户导航返回后,在主屏幕上伴随着一个大横幅。

我的androidx.core:core-ktx是1.9.0版本,gradleplugin是7.3.1

我试过:

override fun onNotificationPosted(sbn: StatusBarNotification) {
     val priority = sbn.notification.priority
}

但它已被弃用,应该使用 NotificationChannel.getImportance() 代替。

我也试过了,但是我收到每个通知的通道对象都是空的,而且我无法访问重要性字段:

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
      val notificationManager = getSystemService(NOTIFICATION_SERVICE) as NotificationManager
      val channel = notificationManager.getNotificationChannel(sbn.notification.channelId)
      val importance = channel?.importance ?: 0
}

NotificationManager 在其列表中没有任何频道,因为我没有创建任何频道。我刚收到系统通知。

我检查了 android.permission.ACCESS_NOTIFICATION_POLICY 但它已经被授予。当我检查 notificationManager.isNotificationPolicyAccessGranted 它返回 true。所以问题不存在。

我也试过这个,但是每个通知的重要性都是0。

  val notificationClass = notification.javaClass
        try {
            val field = notificationClass.getField("priority")
            val importance = field.getInt(notification)
            Log.d("MyNotificationListener", "Importance level: $importance")
        } catch (e: Exception) {
            Log.e("MyNotificationListener", "Failed to get importance level", e)
        }

我一直在寻找NotificationCompat,但我不知道如何获得优先权。

我试过:

 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
     val chlist = getNotificationChannels(sbn.opPkg,sbn.user)
 }

但是它会引发安全异常,因为无法访问给定用户的通知,我不明白为什么。

有人知道接下来要尝试什么吗?

感谢安万斯

android kotlin notifications android-notifications android-tv
1个回答
0
投票

这是我们在触发通知时从服务器端收到的示例 json 文件。

{
  "message": {
    "notification": {
      "title": "",
      "body": "",
      "android_channel_id": "channel_id" // here is channel id 
    },
    "android": {
      "priority": "high",  // Priorities
      "notification": {
        "click_action": "OPEN_ACTIVITY_ACTION"
      }
    },
    "data": {
      "key1": "value",
      "key2": "value2"
    },
    "token": "Device Token"
  }
} 
© www.soinside.com 2019 - 2024. All rights reserved.