You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Android点击通知按钮无法关闭通知问题排查及修改方案咨询

问题修复方案

通知点击按钮无法关闭的核心原因是PendingIntent配置错误,按以下步骤修改即可:

  • 修改PendingIntent的Flag配置:当前使用的FLAG_IMMUTABLE会导致Intent携带的notificationId额外参数无法被接收器正确读取,需要根据安卓版本调整为支持更新额外参数的Flag
  • 修改PendingIntent的请求码:所有通知的关闭PendingIntent都使用固定请求码0会导致多通知场景下额外参数被覆盖,需要将请求码改为和当前通知的notificationId一致,保证每个通知的关闭操作唯一
  • 不要将0作为通知的唯一ID,避免和参数默认回退值冲突导致取消逻辑异常

修改后的sendNotification方法代码

private fun sendNotification(){
       val closeIntent = Intent(this, CloseNotificationReceiver::class.java)
           .putExtra("ID", notificationId)
       val closeFlag = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
           // 安卓12及以上需要指定FLAG_MUTABLE才能读取Intent携带的额外参数
           PendingIntent.FLAG_MUTABLE or PendingIntent.FLAG_UPDATE_CURRENT
       } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
           PendingIntent.FLAG_UPDATE_CURRENT
       } else {
           0
       }
       // 请求码改为和当前通知ID一致,保证每个PendingIntent唯一
       val closePendingIntent = PendingIntent
           .getBroadcast(this, notificationId, closeIntent, closeFlag)

    val builder = NotificationCompat.Builder(this, CHANNEL_ID)
        /// 保留原有其他通知配置代码
        .addAction(R.drawable.ic_launcher_background, "400 мл", closePendingIntent)
        //// 保留原有其他通知配置代码

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

CloseNotificationReceiver代码(可保留原有逻辑,仅建议增加日志排查问题)

class CloseNotificationReceiver : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
    val id = intent.getIntExtra("ID", 0)
    // 可选增加日志,确认接收器拿到的通知ID是否正确
    // Log.d("通知关闭", "待关闭通知ID:$id")
    NotificationManagerCompat.from(context).cancel(id)
}}

AndroidManifest.xml配置无需修改,原有配置已符合要求

内容的提问来源于stack exchange,提问作者alon1

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.23 21:45:02