HarmonyOS的后台提醒

133 阅读1分钟

一、后台代理提醒的业务类型

  • 倒计时类:基于倒计时的提醒功能,适用于短时的计时提醒业务。
  • 日历类:基于日历的提醒功能,适用于较长时间的提醒业务。
  • 闹钟类:基于时钟的提醒功能,适用于指定时刻的提醒业务。

注: 后台代理提醒就是由系统后台进程代理应用的提醒功能。后台代理提醒服务通过reminderAgentManager模块提供提醒定义、创建提醒、取消提醒等能力。

二、使用后台代理提醒

2.1添加提醒权限

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

2.2导入后台代理提醒reminderAgentManager模块

import { reminderAgentManager } from '@kit.BackgroundTasksKit';

2.3创建提醒实例

import { reminderAgentManager } from '@kit.BackgroundTasksKit';
   
  private initReminder(item: ReminderItem): reminderAgentManager.ReminderRequestAlarm {
    return {
      reminderType: item.remindType,
      hour: item.hour,
      minute: item.minute,
      daysOfWeek: item.repeatDays,
      title: item.name,
      ringDuration: item.duration * CommonConstants.DEFAULT_TOTAL_MINUTE,
      snoozeTimes: item.intervalTimes,
      timeInterval: item.intervalMinute * CommonConstants.DEFAULT_TOTAL_MINUTE,
      actionButton: [
        {
          title: '关闭',
          type: reminderAgentManager.ActionButtonType.ACTION_BUTTON_TYPE_CLOSE
        },
      ],
      wantAgent: {
        pkgName: CommonConstants.BUNDLE_NAME,
        abilityName: CommonConstants.ABILITY_NAME
      },
      notificationId: item.notificationId,
    }
  }
}

2.4发布提醒

import { reminderAgentManager } from '@kit.BackgroundTasksKit';
// ...

export class ReminderService {
  public addReminder(alarmItem: ReminderItem, callback?: (reminderId: number) => void) {
  ///调用创建提醒实例方法
    let reminder = this.initReminder(alarmItem);
    ///发布提醒并获取提醒任务id
    reminderAgentManager.publishReminder(reminder, (err, reminderId) => {
      if (callback != null) {
        callback(reminderId);
      }
    });
  }
}

2.5删除提醒

如果需要删除提醒,可以调用cancelReminder()接口实现,并传入发布提醒返回的提醒任务id。

reminderAgentManager.cancelReminder(reminderId);

注意:如果需要修改提醒,则需要先进行旧提醒的删除,再新增新的提醒。