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

如何使用FCM及REST API实现定时推送通知?

问题分析

你的定时推送不生效,核心是用错了FCM的定时参数规则:你把event_time嵌套在notification和data字段里,但FCM的REST API根本不识别这个位置的定时配置,而且正确的定时触发参数是schedule_time,必须放在请求体的顶层。

正确实现方案

不管是用FCM还是其REST API发送定时推送,都得遵循FCM的参数规范,以下是修正步骤和代码:

1. 生成符合要求的定时时间

FCM要求schedule_time必须是RFC3339格式的UTC时间字符串(比如2024-05-20T15:30:00Z),不能用毫秒时间戳,且定时时间必须在当前时间之后的7天范围内。

2. 调整请求体结构

把schedule_time放在请求体顶层,和registration_ids、notification同级;另外可以配合设置delivery_priority为normal(默认是high,会强制立即推送),优化推送时机。

修正后的完整代码

sendFCM() async {
  const postUrl = 'https://fcm.googleapis.com/fcm/send';
  // 生成1分钟后的UTC时间,转为RFC3339格式
  DateTime scheduledDateTime = DateTime.now().add(const Duration(minutes: 1));
  String scheduleTime = scheduledDateTime.toUtc().toIso8601String();

  Map<String, dynamic> data = {
    "registration_ids": [
      "dqR9vyp4R2W9keBUKdd66a:APA91bEuSc8r3bhjz0oZsA9uiM9-SyIttNgnJIujhB7K9OoqXNGFb5doim0CAyXCYRnAreIP5KUAWLLf3Fn6jzD_qptHfgxbZT5dGR75ntAiw-hqoxQTWG2RTei5IIYnOY46ECzLv-QW"
    ],
    "collapse_key": "type_a",
    // 顶层配置定时参数
    "schedule_time": scheduleTime,
    // 可选:设置普通优先级,避免强制立即推送
    "delivery_priority": "normal",
    "notification": {
      "title": "title",
      "body": "body"
    },
    'data': {
      "title": "title",
      "body": "body"
    },
  };

  final response =
      await http.post(Uri.parse(postUrl), body: json.encode(data), headers: {
    'content-type': 'application/json',
    'Authorization': "Key=AAA*****************************FCsxhvLO6C7XYCAI-rfPURYBp"
  });

  print(response.body);
  return response.statusCode == 200;
}
关键注意事项
  • schedule_time必须是UTC时间,格式严格遵循RFC3339,不能用毫秒时间戳。
  • 定时推送的时间不能超过当前时间7天,否则FCM会直接拒绝请求。
  • 如果设备离线,FCM会在设备上线且到达定时时间后再推送通知。
  • 定时参数绝对不能放在notification或data字段里,FCM不会读取这些位置的定时配置。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 05:36:04