HarmonyOS APP开发中提醒通知小实践

举报
Jack20 发表于 2026/06/20 13:50:07 2026/06/20
【摘要】 HarmonyOS APP开发中提醒通知小实践核心要点:提醒通知(Reminder Agent)是 HarmonyOS 提供的"定时闹钟"机制,支持倒计时、日历和闹钟三种提醒类型,即使应用被杀死也能准时"敲门"。 一、背景与动机你有没有这样的经历?设了一个吃药提醒,结果手机重启后提醒就没了;或者设了一个会议提醒,结果应用被系统杀掉后提醒也没了。这种"不靠谱"的提醒,还不如不用。Harmon...

HarmonyOS APP开发中提醒通知小实践

核心要点:提醒通知(Reminder Agent)是 HarmonyOS 提供的"定时闹钟"机制,支持倒计时、日历和闹钟三种提醒类型,即使应用被杀死也能准时"敲门"。


一、背景与动机

你有没有这样的经历?设了一个吃药提醒,结果手机重启后提醒就没了;或者设了一个会议提醒,结果应用被系统杀掉后提醒也没了。这种"不靠谱"的提醒,还不如不用。

HarmonyOS 的 reminderAgentManager 就是为了解决这个问题而生的。它是一个系统级的提醒代理服务——你把提醒的需求"委托"给系统,系统会在指定的时间点替你发出通知。即使你的应用进程已经被杀掉、手机已经重启,只要提醒还在系统的"日程表"上,它就一定会准时触发。

打个比方:普通的通知就像你自己去送信,如果你不在了(应用被杀),信就送不到了。而提醒通知就像把信交给了邮局——就算你不在了,邮局也会按时把信送到。


二、核心原理

2.1 提醒通知架构

图片.png

2.2 三种提醒类型对比

类型 类名 触发方式 适用场景 重复支持
倒计时 ReminderRequestTimer 从发布起倒计时秒数 番茄钟、烹饪计时、运动计时
日历 ReminderRequestCalendar 指定日期时间 会议提醒、日程安排、生日提醒 ✅ 按月/周/日重复
闹钟 ReminderRequestAlarm 指定时分秒 每日闹钟、定时任务 ✅ 按星期重复

2.3 ReminderRequest 基础字段

所有三种提醒类型都继承自 ReminderRequest 基类:

interface ReminderRequest {
  reminderType: reminderAgentManager.ReminderType;  // 提醒类型(必填)
  actionButton?: reminderAgentManager.ActionButton;  // 操作按钮
  wantAgent?: WantAgent;                             // 点击通知后的跳转
  maxScreenDuration?: number;                        // 最大亮屏时间(秒)
  ringDuration?: number;                             // 响铃时长(秒)
  snoozeTimes?: number;                              // 贪睡次数
  timeInterval?: number;                             // 贪睡间隔(秒)
  title?: string;                                    // 提醒标题
  content?: string;                                  // 提醒内容
  expiredContent?: string;                           // 过期后内容
  snoozeContent?: string;                            // 贪睡时内容
  notificationId?: number;                           // 通知ID
  slotType?: notificationManager.SlotType;            // 通知渠道类型
}

2.4 提醒通知生命周期

flowchart LR
    A[创建提醒] --> B[publishReminder 注册]
    B --> C[系统持有提醒]
    C --> D{时间到达}
    D -->|触发| E[系统发布通知]
    E --> F{用户操作}
    F -->|点击| G[WantAgent 跳转]
    F -->|贪睡| H[延迟重新触发]
    F -->|关闭| I[提醒结束]
    H --> D
    
    C --> J[应用可取消]
    J --> K[cancelReminder]
    K --> L[提醒移除]
    
    classDef primary fill:#4CAF50,stroke:#388E3C,color:#fff
    classDef warning fill:#FF9800,stroke:#F57C00,color:#fff
    classDef error fill:#F44336,stroke:#D32F2F,color:#fff
    classDef info fill:#2196F3,stroke:#1976D2,color:#fff
    classDef purple fill:#9C27B0,stroke:#7B1FA2,color:#fff
    
    class A,B,C primary
    class D,E,F info
    class G,H,I warning
    class J,K,L error

2.5 提醒通知与普通通知的区别

特性 普通通知 提醒通知
触发时机 立即 定时
应用被杀后 无法发送 系统代理发送
手机重启后 丢失 系统恢复(部分)
权限要求 通知权限 通知权限 + 提醒权限
最大数量 50条 30个提醒
重复支持 需手动实现 内置支持

三、代码实战

3.1 倒计时提醒:番茄钟实现

倒计时提醒是最简单的提醒类型——从发布时刻起,倒计时指定的秒数后触发。非常适合番茄钟、烹饪计时等场景。

import { reminderAgentManager } from '@kit.ReminderAgentKit';
import { notificationManager } from '@kit.NotificationKit';
import { BusinessError } from '@kit.BasicServicesKit';

@Entry
@Component
struct TimerReminderPage {
  @State statusText: string = '番茄钟就绪';
  @State reminderId: number = -1;  // 提醒ID,用于后续取消

  /**
   * 发布倒计时提醒 - 番茄钟
   * 25分钟后触发提醒通知
   */
  async startPomodoro(): Promise<void> {
    try {
      // 构建倒计时提醒请求
      const timerRequest: reminderAgentManager.ReminderRequestTimer = {
        reminderType: reminderAgentManager.ReminderType.REMINDER_TYPE_TIMER,
        triggerTimeInSeconds: 25 * 60,  // 25分钟 = 1500秒
        title: '番茄钟',
        content: '25分钟专注时间结束,休息一下吧!',
        expiredContent: '番茄钟已过期',
        ringDuration: 10,       // 响铃10秒
        snoozeTimes: 1,         // 允许贪睡1次
        timeInterval: 5 * 60,   // 贪睡间隔5分钟
        snoozeContent: '5分钟后再次提醒',
        slotType: notificationManager.SlotType.SOCIAL_COMMUNICATION,
        actionButton: [
          {
            title: '开始休息',
            type: reminderAgentManager.ActionButtonType.ACTION_BUTTON_TYPE_CUSTOM
          },
          {
            title: '关闭',
            type: reminderAgentManager.ActionButtonType.ACTION_BUTTON_TYPE_CLOSE
          }
        ]
      };

      // 发布提醒
      this.reminderId = await reminderAgentManager.publishReminder(timerRequest);
      this.statusText = `🍅 番茄钟已启动\n提醒ID: ${this.reminderId}\n25分钟后提醒`;
      console.info(`[提醒] 番茄钟发布成功,ID: ${this.reminderId}`);
    } catch (err) {
      const error = err as BusinessError;
      this.statusText = `启动失败: ${error.message}`;
      console.error(`[提醒] 发布失败: ${error.code}`);
    }
  }

  /**
   * 发布短时倒计时 - 烹饪计时器
   * 3分钟后触发提醒
   */
  async startCookingTimer(): Promise<void> {
    try {
      const timerRequest: reminderAgentManager.ReminderRequestTimer = {
        reminderType: reminderAgentManager.ReminderType.REMINDER_TYPE_TIMER,
        triggerTimeInSeconds: 3 * 60,  // 3分钟
        title: '烹饪提醒',
        content: '3分钟到了,请检查食物状态',
        ringDuration: 15,
        slotType: notificationManager.SlotType.SERVICE_INFORMATION
      };

      const id = await reminderAgentManager.publishReminder(timerRequest);
      this.statusText = `🍳 烹饪计时器已启动\n提醒ID: ${id}\n3分钟后提醒`;
    } catch (err) {
      const error = err as BusinessError;
      this.statusText = `启动失败: ${error.message}`;
    }
  }

  /**
   * 取消当前提醒
   */
  async cancelCurrentReminder(): Promise<void> {
    if (this.reminderId === -1) {
      this.statusText = '没有活跃的提醒';
      return;
    }

    try {
      await reminderAgentManager.cancelReminder(this.reminderId);
      this.statusText = `提醒 #${this.reminderId} 已取消`;
      this.reminderId = -1;
      console.info('[提醒] 取消成功');
    } catch (err) {
      const error = err as BusinessError;
      this.statusText = `取消失败: ${error.message}`;
    }
  }

  /**
   * 获取所有已发布的提醒
   */
  async getValidReminders(): Promise<void> {
    try {
      const reminders = await reminderAgentManager.getValidReminders();
      if (reminders.length === 0) {
        this.statusText = '当前没有活跃的提醒';
        return;
      }

      const info = reminders.map((r, i) => {
        const typeNames = ['倒计时', '日历', '闹钟'];
        return `${i + 1}. 类型: ${typeNames[r.reminderType] || '未知'} | ID: ${r.reminderId} | 标题: ${r.title || '无'}`;
      }).join('\n');

      this.statusText = `${reminders.length} 个活跃提醒:\n${info}`;
    } catch (err) {
      const error = err as BusinessError;
      this.statusText = `查询失败: ${error.message}`;
    }
  }

  build() {
    Scroll() {
      Column({ space: 16 }) {
        Text('倒计时提醒')
          .fontSize(24)
          .fontWeight(FontWeight.Bold)

        Text(this.statusText)
          .fontSize(14)
          .width('90%')
          .padding(16)
          .borderRadius(12)
          .backgroundColor('#F0F4F8')
          .minHeight(100)

        Button('🍅 启动番茄钟 (25分钟)')
          .width('80%')
          .height(50)
          .backgroundColor('#F44336')
          .onClick(() => this.startPomodoro())

        Button('🍳 启动烹饪计时器 (3分钟)')
          .width('80%')
          .height(50)
          .backgroundColor('#FF9800')
          .onClick(() => this.startCookingTimer())

        Button('查看活跃提醒')
          .width('80%')
          .height(45)
          .backgroundColor('#2196F3')
          .onClick(() => this.getValidReminders())

        Button('取消当前提醒')
          .width('80%')
          .height(45)
          .backgroundColor('#757575')
          .onClick(() => this.cancelCurrentReminder())
      }
      .width('100%')
      .padding(20)
    }
    .width('100%')
    .height('100%')
  }
}

3.2 日历提醒:会议与日程

日历提醒是最灵活的提醒类型——可以指定精确的日期时间,还支持按月、周、日重复。适合会议提醒、生日提醒等场景。

import { reminderAgentManager } from '@kit.ReminderAgentKit';
import { notificationManager } from '@kit.NotificationKit';
import { BusinessError } from '@kit.BasicServicesKit';

@Entry
@Component
struct CalendarReminderPage {
  @State statusText: string = '日历提醒就绪';

  /**
   * 发布日历提醒 - 一次性会议
   * 指定精确的日期和时间
   */
  async scheduleMeetingReminder(): Promise<void> {
    try {
      // 构建会议时间:明天的14:00
      const tomorrow = new Date();
      tomorrow.setDate(tomorrow.getDate() + 1);
      tomorrow.setHours(14, 0, 0, 0);

      const calendarRequest: reminderAgentManager.ReminderRequestCalendar = {
        reminderType: reminderAgentManager.ReminderType.REMINDER_TYPE_CALENDAR,
        dateTime: {
          year: tomorrow.getFullYear(),
          month: tomorrow.getMonth() + 1,  // 月份从1开始
          day: tomorrow.getDate(),
          hour: 14,
          minute: 0
        },
        title: '项目评审会议',
        content: '明天14:00,3楼会议室A,请准时参加',
        expiredContent: '会议提醒已过期',
        ringDuration: 10,
        snoozeTimes: 2,         // 允许贪睡2次
        timeInterval: 5 * 60,   // 贪睡间隔5分钟
        snoozeContent: '5分钟后再次提醒会议',
        slotType: notificationManager.SlotType.SERVICE_INFORMATION
      };

      const id = await reminderAgentManager.publishReminder(calendarRequest);
      this.statusText = `📅 会议提醒已设置\n提醒ID: ${id}\n时间: 明天 14:00\n标题: 项目评审会议`;
      console.info(`[日历提醒] 发布成功,ID: ${id}`);
    } catch (err) {
      const error = err as BusinessError;
      this.statusText = `设置失败: ${error.message}`;
    }
  }

  /**
   * 发布日历提醒 - 每周重复的周会
   * 每周一上午9:00触发
   */
  async scheduleWeeklyMeetingReminder(): Promise<void> {
    try {
      const calendarRequest: reminderAgentManager.ReminderRequestCalendar = {
        reminderType: reminderAgentManager.ReminderType.REMINDER_TYPE_CALENDAR,
        dateTime: {
          year: new Date().getFullYear(),
          month: new Date().getMonth() + 1,
          day: new Date().getDate(),
          hour: 9,
          minute: 0
        },
        repeatMonths: [],  // 不按月重复
        repeatDays: [1],   // 每周一触发(1=周一,7=周日)
        title: '周会提醒',
        content: '每周一上午9:00,团队周会',
        ringDuration: 10,
        slotType: notificationManager.SlotType.SERVICE_INFORMATION
      };

      const id = await reminderAgentManager.publishReminder(calendarRequest);
      this.statusText = `📅 周会提醒已设置\n提醒ID: ${id}\n频率: 每周一 09:00`;
    } catch (err) {
      const error = err as BusinessError;
      this.statusText = `设置失败: ${error.message}`;
    }
  }

  /**
   * 发布日历提醒 - 每月重复的生日提醒
   * 每月15号触发
   */
  async scheduleBirthdayReminder(): Promise<void> {
    try {
      const calendarRequest: reminderAgentManager.ReminderRequestCalendar = {
        reminderType: reminderAgentManager.ReminderType.REMINDER_TYPE_CALENDAR,
        dateTime: {
          year: new Date().getFullYear(),
          month: new Date().getMonth() + 1,
          day: 15,
          hour: 8,
          minute: 0
        },
        repeatMonths: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12],  // 每月重复
        repeatDays: [],
        title: '生日提醒',
        content: '今天是重要日子的15号,别忘了送上祝福!',
        ringDuration: 10,
        slotType: notificationManager.SlotType.SOCIAL_COMMUNICATION
      };

      const id = await reminderAgentManager.publishReminder(calendarRequest);
      this.statusText = `🎂 生日提醒已设置\n提醒ID: ${id}\n频率: 每月15号 08:00`;
    } catch (err) {
      const error = err as BusinessError;
      this.statusText = `设置失败: ${error.message}`;
    }
  }

  build() {
    Scroll() {
      Column({ space: 16 }) {
        Text('日历提醒')
          .fontSize(24)
          .fontWeight(FontWeight.Bold)

        Text(this.statusText)
          .fontSize(14)
          .width('90%')
          .padding(16)
          .borderRadius(12)
          .backgroundColor('#F0F4F8')
          .minHeight(100)

        Button('📅 一次性会议提醒(明天14:00)')
          .width('80%')
          .height(50)
          .backgroundColor('#2196F3')
          .onClick(() => this.scheduleMeetingReminder())

        Button('📅 每周周会提醒(周一09:00)')
          .width('80%')
          .height(50)
          .backgroundColor('#4CAF50')
          .onClick(() => this.scheduleWeeklyMeetingReminder())

        Button('🎂 每月生日提醒(15号08:00)')
          .width('80%')
          .height(50)
          .backgroundColor('#9C27B0')
          .onClick(() => this.scheduleBirthdayReminder())

        Button('查看活跃提醒')
          .width('80%')
          .height(45)
          .backgroundColor('#FF9800')
          .onClick(async () => {
            const reminders = await reminderAgentManager.getValidReminders();
            this.statusText = `${reminders.length} 个活跃提醒`;
          })

        Button('取消所有提醒')
          .width('80%')
          .height(45)
          .backgroundColor('#F44336')
          .onClick(async () => {
            await reminderAgentManager.cancelAllReminders();
            this.statusText = '所有提醒已取消';
          })
      }
      .width('100%')
      .padding(20)
    }
    .width('100%')
    .height('100%')
  }
}

3.3 闹钟提醒:每日定时任务

闹钟提醒专注于"每天固定时间"的提醒场景。与日历提醒不同,闹钟提醒更轻量,只需要指定时分和星期几。

import { reminderAgentManager } from '@kit.ReminderAgentKit';
import { notificationManager } from '@kit.NotificationKit';
import { WantAgent, wantAgent } from '@kit.AbilityKit';
import { BusinessError } from '@kit.BasicServicesKit';

@Entry
@Component
struct AlarmReminderPage {
  @State statusText: string = '闹钟提醒就绪';
  @State alarmIds: number[] = [];  // 保存所有闹钟ID

  /**
   * 创建 WantAgent,点击闹钟通知后跳转到应用
   */
  async createWantAgent(): Promise<WantAgent> {
    const wantAgentInfo: wantAgent.WantAgentInfo = {
      wants: [
        {
          bundleName: 'com.example.reminderdemo',
          abilityName: 'EntryAbility'
        }
      ],
      requestCode: 0,
      operationType: wantAgent.OperationType.START_ABILITY,
      wantAgentFlags: [wantAgent.WantAgentFlags.CONSTANT_FLAG]
    };
    return wantAgent.getWantAgent(wantAgentInfo);
  }

  /**
   * 发布闹钟提醒 - 工作日闹钟
   * 周一到周五 7:00 触发
   */
  async scheduleWorkdayAlarm(): Promise<void> {
    try {
      const agent = await this.createWantAgent();

      const alarmRequest: reminderAgentManager.ReminderRequestAlarm = {
        reminderType: reminderAgentManager.ReminderType.REMINDER_TYPE_ALARM,
        hour: 7,
        minute: 0,
        daysOfWeek: [1, 2, 3, 4, 5],  // 周一到周五
        title: '起床闹钟',
        content: '该起床了!新的一天开始了',
        expiredContent: '闹钟已过期',
        ringDuration: 30,       // 响铃30秒
        snoozeTimes: 3,         // 允许贪睡3次
        timeInterval: 5 * 60,   // 贪睡间隔5分钟
        snoozeContent: '再睡5分钟...',
        wantAgent: agent,
        slotType: notificationManager.SlotType.SOCIAL_COMMUNICATION,
        actionButton: [
          {
            title: '起床',
            type: reminderAgentManager.ActionButtonType.ACTION_BUTTON_TYPE_CUSTOM
          },
          {
            title: '关闭',
            type: reminderAgentManager.ActionButtonType.ACTION_BUTTON_TYPE_CLOSE
          }
        ]
      };

      const id = await reminderAgentManager.publishReminder(alarmRequest);
      this.alarmIds.push(id);
      this.statusText = `⏰ 工作日闹钟已设置\n提醒ID: ${id}\n时间: 周一至周五 07:00\n贪睡: 3次 × 5分钟`;
      console.info(`[闹钟] 发布成功,ID: ${id}`);
    } catch (err) {
      const error = err as BusinessError;
      this.statusText = `设置失败: ${error.message}`;
    }
  }

  /**
   * 发布闹钟提醒 - 周末闹钟
   * 周六和周日 9:00 触发
   */
  async scheduleWeekendAlarm(): Promise<void> {
    try {
      const agent = await this.createWantAgent();

      const alarmRequest: reminderAgentManager.ReminderRequestAlarm = {
        reminderType: reminderAgentManager.ReminderType.REMINDER_TYPE_ALARM,
        hour: 9,
        minute: 0,
        daysOfWeek: [6, 7],  // 周六、周日
        title: '周末闹钟',
        content: '周末好!今天有什么安排?',
        ringDuration: 20,
        snoozeTimes: 2,
        timeInterval: 10 * 60,  // 贪睡间隔10分钟
        snoozeContent: '再睡10分钟...',
        wantAgent: agent,
        slotType: notificationManager.SlotType.SOCIAL_COMMUNICATION
      };

      const id = await reminderAgentManager.publishReminder(alarmRequest);
      this.alarmIds.push(id);
      this.statusText = `⏰ 周末闹钟已设置\n提醒ID: ${id}\n时间: 周六日 09:00`;
    } catch (err) {
      const error = err as BusinessError;
      this.statusText = `设置失败: ${error.message}`;
    }
  }

  /**
   * 发布闹钟提醒 - 午休提醒
   * 每天中午 13:00 触发
   */
  async scheduleLunchBreakAlarm(): Promise<void> {
    try {
      const alarmRequest: reminderAgentManager.ReminderRequestAlarm = {
        reminderType: reminderAgentManager.ReminderType.REMINDER_TYPE_ALARM,
        hour: 13,
        minute: 0,
        daysOfWeek: [1, 2, 3, 4, 5, 6, 7],  // 每天
        title: '午休提醒',
        content: '午休时间到了,适当休息下午更有精神',
        ringDuration: 5,
        slotType: notificationManager.SlotType.SERVICE_INFORMATION
      };

      const id = await reminderAgentManager.publishReminder(alarmRequest);
      this.alarmIds.push(id);
      this.statusText = `💤 午休提醒已设置\n提醒ID: ${id}\n时间: 每天 13:00`;
    } catch (err) {
      const error = err as BusinessError;
      this.statusText = `设置失败: ${error.message}`;
    }
  }

  /**
   * 取消所有闹钟提醒
   */
  async cancelAllAlarms(): Promise<void> {
    try {
      await reminderAgentManager.cancelAllReminders();
      this.alarmIds = [];
      this.statusText = '所有提醒已取消';
      console.info('[闹钟] 所有提醒已取消');
    } catch (err) {
      const error = err as BusinessError;
      this.statusText = `取消失败: ${error.message}`;
    }
  }

  build() {
    Scroll() {
      Column({ space: 16 }) {
        Text('闹钟提醒')
          .fontSize(24)
          .fontWeight(FontWeight.Bold)

        Text(this.statusText)
          .fontSize(14)
          .width('90%')
          .padding(16)
          .borderRadius(12)
          .backgroundColor('#F0F4F8')
          .minHeight(100)

        Button('⏰ 工作日闹钟(周一至周五 07:00)')
          .width('80%')
          .height(50)
          .backgroundColor('#F44336')
          .onClick(() => this.scheduleWorkdayAlarm())

        Button('😴 周末闹钟(周六日 09:00)')
          .width('80%')
          .height(50)
          .backgroundColor('#4CAF50')
          .onClick(() => this.scheduleWeekendAlarm())

        Button('💤 午休提醒(每天 13:00)')
          .width('80%')
          .height(50)
          .backgroundColor('#FF9800')
          .onClick(() => this.scheduleLunchBreakAlarm())

        Button('查看活跃提醒')
          .width('80%')
          .height(45)
          .backgroundColor('#2196F3')
          .onClick(async () => {
            const reminders = await reminderAgentManager.getValidReminders();
            this.statusText = `${reminders.length} 个活跃提醒`;
          })

        Button('取消所有提醒')
          .width('80%')
          .height(45)
          .backgroundColor('#757575')
          .onClick(() => this.cancelAllAlarms())
      }
      .width('100%')
      .padding(20)
    }
    .width('100%')
    .height('100%')
  }
}

四、踩坑与注意事项

4.1 提醒数量限制

系统对每个应用的提醒数量有上限(通常为30个)。超过限制后,publishReminder() 会抛出异常。

// ❌ 错误示范:无限创建提醒
for (let i = 0; i < 100; i++) {
  await reminderAgentManager.publishReminder({...});  // 超过30个后会报错!
}

// ✅ 正确做法:发布前检查数量
const reminders = await reminderAgentManager.getValidReminders();
if (reminders.length >= 30) {
  console.warn('提醒数量已达上限');
  // 先取消一些旧的提醒
  await reminderAgentManager.cancelReminder(reminders[0].reminderId);
}

4.2 权限声明

提醒通知需要额外的权限声明,在 module.json5 中必须添加:

{
  "module": {
    "requestPermissions": [
      {
        "name": "ohos.permission.PUBLISH_AGENT_REMINDER"
      }
    ]
  }
}

如果不声明这个权限,publishReminder() 会抛出权限异常。

4.3 月份从1开始

日历提醒的 dateTime.month 字段是从 1 开始的(1=一月),而不是 JavaScript Date 的从0开始。这是一个容易踩的坑:

// ❌ 错误:使用了 Date.getMonth() 的返回值(0-11)
month: new Date().getMonth()  // 如果是1月,这里返回0

// ✅ 正确:月份需要 +1
month: new Date().getMonth() + 1  // 1月返回1

4.4 repeatDays 的星期编码

闹钟提醒的 daysOfWeek 和日历提醒的 repeatDays 使用相同的编码:1=周一,7=周日。注意不是0-6!

// ❌ 错误理解:以为0=周日
daysOfWeek: [0, 1, 2, 3, 4, 5]  // 0是无效值!

// ✅ 正确:1=周一,7=周日
daysOfWeek: [1, 2, 3, 4, 5]  // 周一到周五
daysOfWeek: [6, 7]            // 周六和周日

4.5 贪睡功能的限制

贪睡次数(snoozeTimes)和贪睡间隔(timeInterval)有以下限制:

  • snoozeTimes 最大值为 3
  • timeInterval 最小值为 5分钟(300秒)
  • 贪睡功能仅在用户点击"贪睡"按钮时生效,不会自动贪睡

4.6 应用卸载后提醒自动清除

当应用被卸载时,系统会自动清除该应用发布的所有提醒。这是系统行为,无需手动处理。

4.7 手机重启后的恢复

手机重启后,已注册的提醒会被系统自动恢复。但有一个前提:提醒的触发时间必须在重启后的未来。如果重启时提醒时间已过,该提醒会被自动丢弃。


五、HarmonyOS 6 适配

5.1 API 变更

变更项 HarmonyOS 5 HarmonyOS 6
模块路径 @ohos.reminderAgentManager @kit.ReminderAgentKit(兼容)
提醒数量上限 30个 50个
贪睡次数上限 3次 5次
新增类型 新增 REMINDER_TYPE_EVENT(事件提醒)
精确度 分钟级 秒级精确度

5.2 迁移指南

  1. 模块导入更新:HarmonyOS 6 推荐使用 @kit.ReminderAgentKit 导入,但旧的 @ohos.reminderAgentManager 路径仍然兼容。

  2. 秒级精确度:HarmonyOS 6 的日历提醒支持秒级精确度,dateTime 对象新增了 second 字段:

// HarmonyOS 6 新增秒级精确度
const calendarRequest = {
  dateTime: {
    year: 2026,
    month: 6,
    day: 20,
    hour: 14,
    minute: 30,
    second: 0  // 新增:秒级精确度
  }
};
  1. 事件提醒:HarmonyOS 6 新增了事件提醒类型,适合基于系统日历事件的提醒场景。

六、总结

mindmap
  root((提醒通知))
    三种类型
      倒计时 REMINDER_TYPE_TIMER
        triggerTimeInSeconds
        番茄钟/烹饪计时
        不支持重复
      日历 REMINDER_TYPE_CALENDAR
        dateTime 精确日期
        repeatMonths 按月重复
        repeatDays 按周重复
        会议/生日/日程
      闹钟 REMINDER_TYPE_ALARM
        hour + minute
        daysOfWeek 按星期
        每日闹钟/定时任务
    核心API
      publishReminder 发布提醒
      cancelReminder 取消提醒
      cancelAllReminders 取消全部
      getValidReminders 查询活跃提醒
    特殊功能
      贪睡 snoozeTimes + timeInterval
      操作按钮 actionButton
      WantAgent 点击跳转
      过期内容 expiredContent
    注意事项
      30个提醒上限
      权限 PUBLISH_AGENT_REMINDER
      月份从1开始
      星期1-7编码
      贪睡最多3次
      重启后自动恢复
知识点 要点
倒计时提醒 ReminderRequestTimer,指定秒数后触发,适合计时场景
日历提醒 ReminderRequestCalendar,指定日期时间,支持月/周重复
闹钟提醒 ReminderRequestAlarm,指定时分和星期,适合每日闹钟
贪睡功能 snoozeTimes + timeInterval,最多3次,间隔最少5分钟
权限声明 必须声明 ohos.permission.PUBLISH_AGENT_REMINDER
月份编码 dateTime.month 从1开始,不是0
星期编码 daysOfWeek 中1=周一,7=周日
系统代理 应用被杀后系统仍会按时触发提醒

提醒通知是"定心丸"——把定时任务交给系统,应用就可以安心退场了。下一篇我们将探讨通知监听,看看如何"监听"其他应用的通知,实现通知的拦截、转发和智能管理。

【声明】本内容来自华为云开发者社区博主,不代表华为云及华为云开发者社区的观点和立场。转载时必须标注文章的来源(华为云社区)、文章链接、文章作者等基本信息,否则作者和本社区有权追究责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@huaweicloud.com
  • 点赞
  • 收藏
  • 关注作者

评论(0

0/1000
抱歉,系统识别当前为高风险访问,暂不支持该操作

全部回复

上滑加载中

设置昵称

在此一键设置昵称,即可参与社区互动!

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。