Ionic Local Notification每日推送两次异常:仅触发最后ID对应时间
解决Ionic本地通知仅触发最后一个ID的问题
Hey there! I’ve run into this exact issue before with Ionic Local Notifications—let’s break down why only your last notification is firing and fix it up.
核心问题诊断
9 times out of 10, this happens because you’re either:
- Reusing the same notification configuration object for both alerts (since objects are reference types, modifying it for the second notification overwrites the first one’s settings)
- Accidentally scheduling notifications with conflicting logic (like misconfiguring repeat triggers or overwriting the same ID)
修复步骤 & 示例代码
1. 为每个通知创建独立的配置对象
绝对不要复用同一个配置对象来创建多个通知,要为每个每日提醒单独生成配置,避免设置互相覆盖。
错误写法(会导致覆盖):
// ❌ 糟糕的写法:复用同一个对象 let notificationConfig = { id: 1, title: "Morning Alert", text: "Start your day!", trigger: { at: new Date(new Date().setHours(8, 0, 0)), every: "day" } }; // 修改同一个对象会覆盖第一个通知的配置 notificationConfig.id = 2; notificationConfig.text = "Wind down for the night!"; notificationConfig.trigger.at = new Date(new Date().setHours(20, 0, 0)); LocalNotifications.schedule([notificationConfig]);
正确写法(独立对象):
// ✅ 正确的写法:每个通知用独立配置 const morningAlert = { id: 1, // 唯一ID title: "Morning Reminder", text: "Time to kick off your day!", trigger: { at: new Date(new Date().setHours(8, 0, 0, 0)), // 明确设置时/分/秒/毫秒 every: "day" }, foreground: true // 可选:APP前台运行时也显示通知 }; const eveningAlert = { id: 2, // 不同的唯一ID title: "Evening Reminder", text: "Time to wrap up and relax!", trigger: { at: new Date(new Date().setHours(20, 0, 0, 0)), every: "day" }, foreground: true }; // 同时调度两个通知 await LocalNotifications.schedule([morningAlert, eveningAlert]);
2. 验证权限并避免重复调度
- 首先确保已经向用户请求了通知权限——没有权限的话通知根本无法触发。
- 另外,不要每次APP启动都重复调度同一ID的通知(这会覆盖已存在的通知),调度前先检查通知是否已存在。
async setupDailyNotifications() { // 先请求权限 const permission = await LocalNotifications.requestPermissions(); if (!permission.granted) { console.log("Notification permission denied"); return; } // 检查通知是否已存在,避免重复覆盖 const hasMorningAlert = await LocalNotifications.isPresent(1); const hasEveningAlert = await LocalNotifications.isPresent(2); if (!hasMorningAlert) { await LocalNotifications.schedule(morningAlert); } if (!hasEveningAlert) { await LocalNotifications.schedule(eveningAlert); } }
3. 额外排查点
- 检查设备的通知设置:确保你的APP被允许发送通知,且省电模式没有阻止后台触发。
- 先测试特定日期的触发(不用
every: "day"),确认触发逻辑正常后再添加每日重复规则。
内容的提问来源于stack exchange,提问作者indrasaputraahmadi
相关产品推荐
相关产品推荐

