0

android 应用程序,当获取新数据并需要向通知抽屉发布通知时,有时如果前一个通知仍在活动通知列表中(用户没有点击或滑动以关闭它),则更新或替换旧的需要通知。

这里的问题是之前的通知是从 3rd 方 sdk 构建并发布到通知抽屉的,这里我们只能Notification

statusBarNotificationList = ((NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE)).getActiveNotifications())

并从返回的活动状态栏通知列表中找到一个特殊的键

val notificationToReplace: Notification? = null
for (int i = statusBarNotificationList.size() - 1; (i > 0); i--){
    notificationToReplace = If( statusBarNotificationList[i].getNotification().extras.get("theSpecialKey") == "KEY_UPDATE_BY_REPLACE") else null
    if (notificationToReplace != null) break
}
// how to update the notificationToReplace here???

在 google android 通知示例中,它评论:

 *  IMPORTANT NOTE 1: You shouldn't save/modify the resulting Notification object using
 *  its member variables and/or legacy APIs. If you want to retain anything from update
 *  to update, retain the Builder

在这个用例中,它需要更新extra这个现有的活动通知,不能这样做:

    notificationToReplace.extras = newExtra
    notificationMgr.notif(notificationToReplace.getId(), notificationToReplace)

这里不能有原始的 Notification.Builder。

有什么建议吗?

编辑:

看起来问题是无法从 pendingIntent 中获取或更新自定义数据。

这通常是通过 notify() 构建和发布通知的方式。

自定义数据放在intent的extra中,intent放在pendingIntent中。

val intent = Intent(this, AlertDetails::class.java).apply {
    flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK
    putExtra(CUSTOM_MESSAGE_KEY, customData)

}
val pendingIntent: PendingIntent = PendingIntent.getActivity(this, 0, intent, 0)

val builder = NotificationCompat.Builder(this, CHANNEL_ID)
        .setSmallIcon(R.drawable.notification_icon)
        .setContentTitle("My notification")
        .setContentText("Hello World!")
        .setPriority(NotificationCompat.PRIORITY_DEFAULT)
        // Set the intent that will fire when the user taps the notification
        .setContentIntent(pendingIntent)
        .setAutoCancel(true)


with(NotificationManagerCompat.from(this)) {
    notificationManager.notify(notificationId, builder.build())
}

它是IntentpendingIntent中的put,要传入Activity。

override fun onNewIntent(intent: Intent) {
        super.onNewIntent(intent)
        val customData: CustomeData = intent.getParcelableExtra<CustomeData>(CUSTOM_MESSAGE_KEY)
}

因此,如果想重用活动通知但只替换其旧的自定义数据,它必须来自pendingIntent中的意图。

它有办法从pendingIntent中获取意图吗?

4

0 回答 0