【HarmonyOS】通知的基本操作
请求通知授权
应用需要获取用户授权才能发送通知。在通知发布前调用requestEnableNotification()接口,弹窗让用户选择是否允许发送通知。当用户拒绝授权后,将无法通过该接口再次拉起弹窗。如果应用需要向用户再次申请通知授权,则可以使用openNotificationSettings接口拉起通知管理半模态弹窗。
开发步骤
-
导入NotificationManager模块。
import { notificationManager } from '@kit.NotificationKit';import { BusinessError } from '@kit.BasicServicesKit';import { hilog } from '@kit.PerformanceAnalysisKit';import { common } from '@kit.AbilityKit';const TAG: string = '[PublishOperation]';const DOMAIN_NUMBER: number = 0xFF00; -
拉起通知弹窗,向用户请求通知授权。
可通过requestEnableNotification的错误码判断用户是否授权。若返回的错误码为1600004,即为拒绝授权。let context = this.getUIContext().getHostContext() as common.UIAbilityContext;notificationManager.isNotificationEnabled().then((data: boolean) => {hilog.info(DOMAIN_NUMBER, TAG, "isNotificationEnabled success, data: " + JSON.stringify(data));if(!data){notificationManager.requestEnableNotification(context).then(() => {hilog.info(DOMAIN_NUMBER, TAG, `[ANS] requestEnableNotification success`);}).catch((err: BusinessError) => {if(1600004 == err.code){hilog.error(DOMAIN_NUMBER, TAG, `[ANS] requestEnableNotification refused, code is ${err.code}, message is ${err.message}`);} else {hilog.error(DOMAIN_NUMBER, TAG, `[ANS] requestEnableNotification failed, code is ${err.code}, message is ${err.message}`);}});}}).catch((err: BusinessError) => {hilog.error(DOMAIN_NUMBER, TAG, `isNotificationEnabled fail, code is ${err.code}, message is ${err.message}`);}); -
(可选)拉起通知管理半模态弹窗,向用户再次申请通知授权。
let context = this.getUIContext().getHostContext() as common.UIAbilityContext;notificationManager.isNotificationEnabled().then((data: boolean) => {hilog.info(DOMAIN_NUMBER, TAG, "isNotificationEnabled success, data: " + JSON.stringify(data));if(!data){notificationManager.openNotificationSettings(context).then(() => {hilog.info(DOMAIN_NUMBER, TAG, `[ANS] openNotificationSettings success`);}).catch((err: BusinessError) => {hilog.error(DOMAIN_NUMBER, TAG, `[ANS] openNotificationSettings failed, code is ${err.code}, message is ${err.message}`);});}}).catch((err: BusinessError) => {hilog.error(DOMAIN_NUMBER, TAG, `isNotificationEnabled fail, code is ${err.code}, message is ${err.message}`);});
管理通知角标
针对未读的通知,系统提供了角标设置接口,将未读通知个数显示在桌面图标的右上角角标上。
通知增加时,角标上显示的未读通知个数需要增加。
通知被查看后,角标上显示的未读通知个数需要减少,没有未读通知时,不显示角标。
接口说明
当角标设定个数取值小于或等于0时,表示清除角标。取值大于99时,通知角标将显示99+。
- 增加角标数,支持如下两种方法:
- 发布通知时,在NotificationRequest的badgeNumber字段里携带,桌面收到通知后,在原角标数上累加、呈现。
- 调用接口**setBadgeNumber()**设置,桌面按设置的角标数呈现。
- 减少角标数,目前仅支持通过**setBadgeNumber()**设置。
开发步骤
-
导入NotificationManager模块。
-
增加角标个数。
发布通知在NotificationRequest的badgeNumber字段里携带,可参考通知发布。示例为调用setBadgeNumber接口增加角标,在发布完新的通知后,调用该接口。
let badgeNumber: number = 9;notificationManager.setBadgeNumber(badgeNumber).then(() => {hilog.info(DOMAIN_NUMBER, TAG, `Succeeded in setting badge number.`);}).catch((err: BusinessError) => {hilog.error(DOMAIN_NUMBER, TAG, `Failed to set badge number. Code is ${err.code}, message is ${err.message}`);}); -
减少角标个数。
let badgeNumber: number = 8;notificationManager.setBadgeNumber(badgeNumber).then(() => {hilog.info(DOMAIN_NUMBER, TAG, `Succeeded in setting badge number.`);}).catch((err: BusinessError) => {hilog.error(DOMAIN_NUMBER, TAG, `Failed to set badge number. Code is ${err.code}, message is ${err.message}`);});
常见问题
由于setBadgeNumber为异步接口,使用setBadgeNumber连续设置角标时,为了确保执行顺序符合预期,需要确保上一次设置完成后才能进行下一次设置。
-
反例
每次接口调用是相互独立的、没有依赖关系的,实际执行时无法保证调用顺序。let badgeNumber: number = 10;notificationManager.setBadgeNumber(badgeNumber).then(() => {hilog.info(DOMAIN_NUMBER, TAG, `setBadgeNumber 10 success.`);}).catch((err: BusinessError) => {hilog.error(DOMAIN_NUMBER, TAG, `Failed to set badge number. Code is ${err.code}, message is ${err.message}`);});badgeNumber = 11;notificationManager.setBadgeNumber(badgeNumber).then(() => {hilog.info(DOMAIN_NUMBER, TAG, `setBadgeNumber 11 success.`);}).catch((err: BusinessError) => {hilog.error(DOMAIN_NUMBER, TAG, `Failed to set badge number. Code is ${err.code}, message is ${err.message}`);}); -
正例
多次接口调用存在依赖关系,确保上一次设置完成后才能进行下一次设置。let badgeNumber: number = 10;notificationManager.setBadgeNumber(badgeNumber).then(() => {hilog.info(DOMAIN_NUMBER, TAG, `setBadgeNumber 10 success.`);badgeNumber = 11;notificationManager.setBadgeNumber(badgeNumber).then(() => {hilog.info(DOMAIN_NUMBER, TAG, `setBadgeNumber 11 success.`);}).catch((err: BusinessError) => {hilog.error(DOMAIN_NUMBER, TAG, `Failed to set badge number. Code is ${err.code}, message is ${err.message}`);});}).catch((err: BusinessError) => {hilog.error(DOMAIN_NUMBER, TAG, `Failed to set badge number. Code is ${err.code}, message is ${err.message}`);});
管理通知渠道
通知渠道类型说明
不同类型的通知渠道对应的通知提醒方式不同,详见下表。其中,Y代表支持,N代表不支持。
说明
用户可以通过“设置 > 通知和状态栏”进入对应的应用,管理该应用的通知渠道。当应用中的“允许通知”开关开启时,横幅通知默认关闭(不支持应用配置、用户可手动开启),锁屏通知、桌面角标、响铃和振动等默认开启。
| SlotType | 取值 | 分类 | 通知中心 | 横幅 | 锁屏 | 铃声/振动 | 状态栏图标 | 自动亮屏 |
|---|---|---|---|---|---|---|---|---|
| UNKNOWN_TYPE | 0 | 未知类型 | Y | N | N | N | N | N |
| SOCIAL_COMMUNICATION | 1 | 社交通信 | Y | Y | Y | Y | Y | Y |
| SERVICE_INFORMATION | 2 | 服务提醒 | Y | Y | Y | Y | Y | Y |
| CONTENT_INFORMATION | 3 | 内容资讯 | Y | N | N | N | N | N |
| CUSTOMER_SERVICE | 5 | 客服消息 | Y | N | N | Y | Y | N |
| OTHER_TYPES | 0xFFFF | 其他 | Y | N | N | N | N | N |
接口说明
通知渠道主要接口如下。
| 接口名 | 描述 |
|---|---|
| addSlot(type: SlotType): Promise | 创建指定类型的通知渠道。 |
| getSlot(slotType: SlotType): Promise | 获取一个指定类型的通知渠道。 |
| removeSlot(slotType: SlotType): Promise | 删除此应用程序指定类型的通知渠道。 |
除了可以使用addSlot()创建通知渠道,还可以在发布通知的NotificationRequest中携带notificationSlotType字段,如果对应渠道不存在,会自动创建。
开发步骤
-
导入notificationManager模块。
-
创建指定类型的通知渠道。
// addSlot回调// 定义创建渠道的回调函数let addSlotCallBack = (err: BusinessError): void => {if (err) {// 若有错误,打印错误日志(错误码和信息)hilog.error(DOMAIN_NUMBER, TAG, `addSlot failed, code is ${err.code}, message is ${err.message}`);} else {// 无错误,打印成功日志hilog.info(DOMAIN_NUMBER, TAG, `addSlot success`);}};// 调用API创建“社交通讯”类型的通知渠道notificationManager.addSlot(notificationManager.SlotType.SOCIAL_COMMUNICATION, addSlotCallBack); -
查询指定类型的通知渠道。
获取对应渠道是否创建以及该渠道支持的通知提醒方式,比如是否有声音提示,是否有震动,锁屏是否可见等。// getSlot回调let getSlotCallback = (err: BusinessError, data: notificationManager.NotificationSlot): void => {if (err) {hilog.error(DOMAIN_NUMBER, TAG, `Failed to get slot. Code is ${err.code}, message is ${err.message}`);} else {hilog.info(DOMAIN_NUMBER, TAG, `Succeeded in getting slot.`);if (data != null) {hilog.info(DOMAIN_NUMBER, TAG, `slot enable status is ${JSON.stringify(data.enabled)}`);hilog.info(DOMAIN_NUMBER, TAG, `vibrationEnabled status is ${JSON.stringify(data.vibrationEnabled)}`);hilog.info(DOMAIN_NUMBER, TAG, `lightEnabled status is ${JSON.stringify(data.lightEnabled)}`);}}}// 指定要查询的渠道类型(社交通讯)let slotType: notificationManager.SlotType = notificationManager.SlotType.SOCIAL_COMMUNICATION;// 调用API查询渠道notificationManager.getSlot(slotType, getSlotCallback); -
删除指定类型的通知渠道。
// removeSlot回调let removeSlotCallback = (err: BusinessError): void => {if (err) {hilog.error(DOMAIN_NUMBER, TAG, `removeSlot failed, code is ${JSON.stringify(err.code)}, message is ${JSON.stringify(err.message)}`);} else {hilog.info(DOMAIN_NUMBER, TAG, "removeSlot success");}}let slotType: notificationManager.SlotType = notificationManager.SlotType.SOCIAL_COMMUNICATION;notificationManager.removeSlot(slotType, removeSlotCallback);
发布通知
发布文本类型通知
文本类型通知主要应用于发送短信息、提示信息等,支持普通文本类型和多行文本类型。
基础类型通知中的内容分类:
| 类型 | 描述 |
|---|---|
| NOTIFICATION_CONTENT_BASIC_TEXT | 普通文本类型。 |
| NOTIFICATION_CONTENT_MULTILINE | 多行文本类型。 |
接口说明
通知发布的详情可通过入参NotificationRequest来进行指定,可以包括通知内容、通知ID、通知的通道类型和通知发布时间等信息。
| 接口名 | 描述 |
|---|---|
| publish(request: NotificationRequest, callback: AsyncCallback): void | 发布通知。 |
开发步骤
- 导入模块。
- 构造NotificationRequest对象,并发布通知。
- 普通文本类型通知由标题、文本内容和附加信息三个字段组成。
let notificationRequest: notificationManager.NotificationRequest = {id: 1,content: {notificationContentType: notificationManager.ContentType.NOTIFICATION_CONTENT_BASIC_TEXT, // 普通文本类型通知normal: {title: 'test_title',text: 'test_text',additionalText: 'test_additionalText',}}};notificationManager.publish(notificationRequest, (err: BusinessError) => {if (err) {hilog.error(DOMAIN_NUMBER, TAG, `Failed to publish notification. Code is ${err.code}, message is ${err.message}`);return;}hilog.info(DOMAIN_NUMBER, TAG, 'Succeeded in publishing notification.');}); - 多行文本类型通知继承了普通文本类型的字段,同时新增了多行文本内容、内容概要和通知展开时的标题。
let notificationRequest: notificationManager.NotificationRequest = {id: 3,content: {notificationContentType: notificationManager.ContentType.NOTIFICATION_CONTENT_MULTILINE, // 多行文本类型通知multiLine: {title: 'test_title',text: 'test_text',briefText: 'test_briefText',longTitle: 'test_longTitle',lines: ['line_01', 'line_02', 'line_03'],}}};// 发布通知notificationManager.publish(notificationRequest, (err: BusinessError) => {if (err) {hilog.error(DOMAIN_NUMBER, TAG, `Failed to publish notification. Code is ${err.code}, message is ${err.message}`);return;}hilog.info(DOMAIN_NUMBER, TAG, 'Succeeded in publishing notification.');});
- 普通文本类型通知由标题、文本内容和附加信息三个字段组成。
发布进度条类型通知
进度条通知也是常见的通知类型,主要应用于文件下载、事务处理进度显示。当前系统提供了进度条模板,发布通知应用设置好进度条模板的属性值,如模板名、模板数据,通过通知子系统发送到通知栏显示。
目前系统模板仅支持进度条模板,通知模板NotificationTemplate中的data参数为用户自定义数据,用于显示与模块相关的数据。
接口说明
isSupportTemplate()是查询模板是否支持接口,目前仅支持进度条模板。
| 接口名 | 描述 |
|---|---|
| isSupportTemplate(templateName: string): Promise | 查询模板是否存在。 |
开发步骤
- 导入模块。
- 查询系统是否支持进度条模板,查询结果为支持downloadTemplate模板类通知。
notificationManager.isSupportTemplate('downloadTemplate').then((data:boolean) => {let isSupportTpl: boolean = data; // isSupportTpl的值为true表示支持downloadTemplate模板类通知,false表示不支持hilog.info(DOMAIN_NUMBER, TAG, `Succeeded in supporting download template notification. data is ${isSupportTpl}`);}).catch((err: BusinessError) => {hilog.error(DOMAIN_NUMBER, TAG, `Failed to support download template notification. Code is ${err.code}, message is ${err.message}`);}); - 构造进度条模板对象,并发布通知。
let notificationRequest: notificationManager.NotificationRequest = {id: 5,content: {notificationContentType: notificationManager.ContentType.NOTIFICATION_CONTENT_BASIC_TEXT,normal: {title: 'test_title',text: 'test_text',additionalText: 'test_additionalText'}},// 构造进度条模板,name字段当前需要固定配置为downloadTemplatetemplate: {name: 'downloadTemplate',data: { title: 'File Title', fileName: 'music.mp4', progressValue: 45 }}}// 发布通知notificationManager.publish(notificationRequest, (err: BusinessError) => {if (err) {hilog.error(DOMAIN_NUMBER, TAG, `Failed to publish notification. Code is ${err.code}, message is ${err.message}`);return;}hilog.info(DOMAIN_NUMBER, TAG, 'Succeeded in publishing notification.');});
为通知添加行为意图
应用向Ability Kit申请WantAgent,并将WantAgent封装至通知中。当发布通知时,用户便可以通过点击通知栏中的消息或按钮,拉起目标应用组件或发布公共事件。
运行机制

接口说明
| 接口名 | 描述 |
|---|---|
| publish(request: NotificationRequest): Promise | 发布通知。 |
| getWantAgent(info: WantAgentInfo, callback: AsyncCallback): void | 创建WantAgent。 |
开发步骤
-
导入模块。
import { notificationManager } from '@kit.NotificationKit';import { wantAgent, WantAgent } from '@kit.AbilityKit';import { BusinessError } from '@kit.BasicServicesKit';import { hilog } from '@kit.PerformanceAnalysisKit';const TAG: string = '[PublishOperation]';const DOMAIN_NUMBER: number = 0xFF00; -
创建WantAgentInfo信息。
-
场景一:创建拉起UIAbility的WantAgent的WantAgentInfo信息。
目标是通过通知触发打开应用内的某个 UI 界面(UIAbility 组件)。例如:点击通知打开应用的 “详情页”“设置页” 等。let wantAgentObj:WantAgent; // 用于保存创建成功的wantAgent对象,后续使用其完成触发的动作。// 通过WantAgentInfo的operationType设置动作类型let wantAgentInfo:wantAgent.WantAgentInfo = {wants: [{deviceId: '',bundleName: 'com.samples.notification', // 需要替换为对应的bundleName。abilityName: 'SecondAbility', // 需要替换为对应的abilityName。action: '',entities: [],uri: '',parameters: {}}],actionType: wantAgent.OperationType.START_ABILITY,requestCode: 0,actionFlags:[wantAgent.WantAgentFlags.CONSTANT_FLAG]}; -
场景二:创建发布公共事件的WantAgent的WantAgentInfo信息。
目标是通过通知触发发送一个系统级的公共事件。例如:点击通知发送 “刷新数据”“更新状态” 等事件,供其他组件处理。let wantAgentObj:WantAgent; // 用于保存创建成功的WantAgent对象,后续使用其完成触发的动作。// 通过WantAgentInfo的operationType设置动作类型let wantAgentInfo:wantAgent.WantAgentInfo = {wants: [{action: 'event_name', // 设置事件名parameters: {},}],actionType: wantAgent.OperationType.SEND_COMMON_EVENT,requestCode: 0,actionFlags: [wantAgent.WantAgentFlags.CONSTANT_FLAG],};
-
-
调用getWantAgent()方法进行创建WantAgent。
// 创建WantAgentwantAgent.getWantAgent(wantAgentInfo, (err: BusinessError, data:WantAgent) => {if (err) {hilog.error(DOMAIN_NUMBER, TAG, `Failed to get want agent. Code is ${err.code}, message is ${err.message}`);return;}hilog.info(DOMAIN_NUMBER, TAG, 'Succeeded in getting want agent.');wantAgentObj = data;}); -
构造NotificationRequest对象,并发布携带WantAgent的通知。
说明如果封装WantAgent至通知消息中,可以点击通知触发WantAgent。当通知消息存在actionButtons时,点击通知会先显示actionButtons,再次点击通知触发WantAgent。
如果封装WantAgent至通知按钮中,点击通知后,该通知下方会出现通知按钮,可以点击按钮触发WantAgent。// 构造NotificationActionButton对象 let actionButton: notificationManager.NotificationActionButton = {title: 'Test_Title',// wantAgentObj使用前需要保证已被赋值(即步骤3执行完成)// 通知按钮的WantAgentwantAgent: wantAgentObj }// 构造NotificationRequest对象 let notificationRequest: notificationManager.NotificationRequest = {content: {notificationContentType: notificationManager.ContentType.NOTIFICATION_CONTENT_BASIC_TEXT,normal: {title: 'Test_Title',text: 'Test_Text',additionalText: 'Test_AdditionalText',},},id: 6,// 通知消息的WantAgentwantAgent: wantAgentObj,// 通知按钮actionButtons: [actionButton],//通知按钮通过NotificationRequest的actionButtons属性挂载到通知上:// 数组形式,可添加多个按钮 }notificationManager.publish(notificationRequest, (err: BusinessError) => {if (err) {hilog.error(DOMAIN_NUMBER, TAG, `Failed to publish notification. Code is ${err.code}, message is ${err.message}`);return;}hilog.info(DOMAIN_NUMBER, TAG, 'Succeeded in publishing notification.'); });
更新通知
更新已发布的通知。主要用于上传下载进度更新、IM会话消息更新等场景。
接口说明
通知发布更新接口说明详见下表,通知更新可通过入参NotificationRequest携带updateOnly字段来指定,不指定该字段默认为false。
- 当updateOnly为true时,若相同ID通知存在,则更新通知;若相同ID通知不存在,则更新失败,不创建新的通知。
- 当updateOnly为false时,若相同ID通知存在,则更新通知;若相同ID通知不存在,则创建通知。
| 接口名 | 描述 |
|---|---|
| publish(request: NotificationRequest, callback: AsyncCallback): void | 发布更新通知。 |
开发步骤
下面以进度条通知发布更新为例。
- 导入模块。
- 发布进度条通知。
代码同发布进度条类型通知开发步骤。 - 通过NotificationRequest接口携带updateOnly字段更新进度条通知。
let notificationRequest: notificationManager.NotificationRequest = {id: 5,updateOnly: true,content: {notificationContentType: notificationManager.ContentType.NOTIFICATION_CONTENT_BASIC_TEXT,normal: {title: 'test_title',text: 'test_text',additionalText: 'test_additionalText'}},// 构造进度条模板,name字段当前需要固定配置为downloadTemplatetemplate: {name: 'downloadTemplate',data: { title: 'File Title', fileName: 'music.mp4', progressValue: 99 }}}// 更新发布通知notificationManager.publish(notificationRequest, (err: BusinessError) => {if (err) {hilog.error(DOMAIN_NUMBER, TAG, `Failed to update notification. Code is ${err.code}, message is ${err.message}`);return;}hilog.info(DOMAIN_NUMBER, TAG, 'Succeeded in updating notification.');});
取消通知
用户收到通知提醒后,点击通知并拉起应用到前台时,应用可以选择取消某条通知或所有通知。
例如,用户收到某个好友的IM消息,点击通知进入应用查看消息后,应用可以取消相关通知提醒。
接口说明
| 接口名 | 描述 |
|---|---|
| cancel(id: number, callback: AsyncCallback): void | 取消指定的通知。 |
| cancelAll(callback: AsyncCallback): void | 取消所有该应用发布的通知。 |
开发步骤
本文以取消文本类型通知为例进行说明,其他类型通知取消操作与此类似。
- 导入模块。
- 发布通知。
参考发布文本类型通知。 - 取消通知。
// 当拉起应用到前台,查看消息后,调用该接口取消通知。notificationManager.cancel(1, (err: BusinessError) => {if (err) {hilog.error(DOMAIN_NUMBER, TAG, `Failed to cancel notification. Code is ${err.code}, message is ${err.message}`);return;}hilog.info(DOMAIN_NUMBER, TAG, 'Succeeded in canceling notification.');});
