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

如何在发送FCM通知时指定Android通知ID以实现通知取消?

如何在FCM消息中指定Android通知ID以实现通知取消?

可以的,后端发送FCM消息时,有两种方式指定Android端的通知ID,满足后续调用NotificationManager.cancel(...)的需求:

1. 发送FCM通知消息时直接指定通知ID

如果后端发送的是FCM通知消息(由FCM服务直接在Android端展示通知),可以在消息payload的android.notification节点下设置notification_id字段,指定自定义的整数ID。示例payload如下:

{
  "to": "目标设备的FCM令牌",
  "notification": {
    "title": "新通知",
    "body": "这是一条可通过指定ID取消的通知"
  },
  "android": {
    "notification": {
      "notification_id": 1001
    }
  }
}

Android端收到这条通知后,系统会使用该notification_id作为通知的唯一标识,后续直接调用NotificationManager.cancel(1001)即可取消这条通知。

2. 发送FCM数据消息,客户端自定义通知ID

如果后端发送的是FCM数据消息(由客户端自行处理并构建通知),可以在data字段中携带自定义的通知ID,客户端收到消息后取出该ID,在调用NotificationManager.notify(...)时使用。示例payload:

{
  "to": "目标设备的FCM令牌",
  "data": {
    "custom_notification_id": "2002",
    "title": "自定义通知",
    "content": "客户端构建的可取消通知"
  }
}

客户端处理逻辑示例(Kotlin):

val notificationId = remoteMessage.data["custom_notification_id"]?.toInt() ?: 0
val notification = NotificationCompat.Builder(context, CHANNEL_ID)
    .setContentTitle(remoteMessage.data["title"])
    .setContentText(remoteMessage.data["content"])
    .build()
NotificationManagerCompat.from(context).notify(notificationId, notification)

后续取消时,直接使用同一个notificationId调用cancel()即可。

注意事项

  • notification_id必须是int32类型的整数,FCM不支持字符串格式的ID。
  • 若使用通知消息的方式,无需客户端额外处理通知ID,系统会自动关联;若使用数据消息,必须确保客户端构建通知时使用后端传入的ID,才能对应到取消操作。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 06:25:27