鸿蒙新特性:@ohos.notificationManager 通知管理实验室实战 —— 发布通知、插槽管理与角标控制 引言通知是应用与用户沟通的第一公里。一条及时、清晰、分类正确的通知能让用户在锁屏上就能获取关键信息点击即可回到应用完成操作。HarmonyOS NEXT 通过ohos.notificationManager模块将通知发布、管理、插槽分类、角标控制等能力统一暴露给开发者。ohos.notificationManager属于kit.NotificationKit是通知管理的核心入口。它最让人惊喜的设计是发布通知无需任何权限。这意味着任何应用都可以自由地推送通知——社交通信、服务提醒、内容资讯、实况窗——只需构建好NotificationRequest请求对象调用publish()即可。本文将深入讲解ohos.notificationManager的通知发布流程、插槽分类机制、状态查询接口、角标控制能力并构建一个通知管理实验室Demo让你在一个页面中完整体验通知的发布、管理、插槽配置和状态追踪。一、API 架构以 NotificationRequest 为核心1.1 核心设计理念ohos.notificationManager的核心能力可以概括为五个字发、管、查、标、跳。发通过publish(request)发布通知通过cancel(id, label)或cancelAll()取消管通过addSlot(type)/getSlots()/removeSlot(type)管理通知插槽分类查通过isNotificationEnabled()/getActiveNotifications()查询通知状态标通过setBadgeNumber(num)/getBadgeNumber()控制桌面角标跳通过requestEnableNotification()请求通知权限应用内弹出系统权限对话框这五个能力构成了完整的通知管理闭环先检查通知是否被用户关闭然后添加通知插槽定义分类接着发布通知查询活跃通知列表控制桌面角标。1.2 NotificationRequest —— 通知构建单元NotificationRequest是所有通知发布操作的核心数据结构interfaceNotificationRequest{id:number;// 通知 ID同 ID 同 label 会替换旧通知content:NotificationContent;// 通知内容标题、正文等notificationSlotType?:SlotType;// 通知插槽类型分类label?:string;// 通知标签用于分组管理deliveryTime?:number;// 定时发送时间戳showDeliveryTime?:boolean;// 是否显示发送时间groupName?:string;// 通知分组名template?:NotificationTemplate;// 通知模板isFloatingIcon?:boolean;// 是否在状态栏显示浮动图标distributedOption?:DistributedOptions;// 分布式通知选项notificationFlags?:NotificationFlags;// 通知标志位}在我们的 Demo 中最小化的NotificationRequest只需要三个字段constrequest:notificationManager.NotificationRequest{id:Date.now(),content:{notificationContentType:notificationManager.ContentType.NOTIFICATION_CONTENT_BASIC_TEXT,normal:{title:通知标题,text:这是通知正文内容}},notificationSlotType:notificationManager.SlotType.SOCIAL_COMMUNICATION};1.3 通知内容类型ContentTypeContentType枚举定义了通知正文的展现形式枚举值说明对应内容字段NOTIFICATION_CONTENT_BASIC_TEXT基本文本normal: { title, text }NOTIFICATION_CONTENT_LONG_TEXT长文本longText: { title, text, longText, ... }NOTIFICATION_CONTENT_MULTILINE多行文本multiLine: { title, text, lines, ... }NOTIFICATION_CONTENT_PICTURE图片通知picture: { title, text, picture, ... }NOTIFICATION_CONTENT_SYSTEM_LIVE_VIEW系统实况窗systemLiveView: { ... }Demo 中使用最基本的NOTIFICATION_CONTENT_BASIC_TEXT足够展示通知发布的核心流程。对于更丰富的通知样式只需切换notificationContentType和对应的content子字段即可。1.4 通知插槽类型SlotType插槽是 HarmonyOS 通知系统中最重要的概念之一——它决定了通知的分类归属和展示行为枚举值数值说明默认重要等级UNKNOWN_TYPE0未知类型LOWSOCIAL_COMMUNICATION1社交通信聊天消息等HIGHSERVICE_INFORMATION2服务信息订单、物流等HIGHCONTENT_INFORMATION3内容资讯新闻、推荐等LOWLIVE_VIEW4实况窗外卖、导航等DEFAULTCUSTOMER_SERVICE5客服消息DEFAULTOTHER_TYPES0xFFFF其他类型LOW每种插槽类型对应一个NotificationSlot对象其中level字段控制通知的展示级别LEVEL_HIGH3级顶部弹出横幅 状态栏图标 锁屏展示LEVEL_DEFAULT2级状态栏图标 锁屏展示不弹出横幅LEVEL_LOW1级仅在通知中心可见不弹出横幅不显示图标二、核心 API 详解2.1 publish() —— 发布通知functionpublish(request:NotificationRequest):Promisevoid;publish()无需任何权限。如果新通知的id和label与已有通知相同新通知会替换旧通知constreq:notificationManager.NotificationRequest{id:Date.now(),content:{notificationContentType:notificationManager.ContentType.NOTIFICATION_CONTENT_BASIC_TEXT,normal:{title:新消息,text:你有一条来自好友的新消息}},notificationSlotType:notificationManager.SlotType.SOCIAL_COMMUNICATION};notificationManager.publish(req).then((){console.log(通知已发布);}).catch((err:Error){console.error(发布失败:,err.message);});发布可能失败的原因包括通知被用户关闭错误码 1600004、通知插槽被禁用错误码 1600005、发布频率超限错误码 1600009等。2.2 cancel() / cancelAll() —— 取消通知functioncancel(id:number,label?:string):Promisevoid;functioncancelAll():Promisevoid;cancel()取消指定 ID 和 label 的通知cancelAll()取消当前应用发布的所有通知。取消操作同样无需权限// 取消特定通知notificationManager.cancel(12345).then((){console.log(通知已取消);});// 取消全部通知notificationManager.cancelAll().then((){console.log(全部通知已清除);});2.3 isNotificationEnabled() —— 检查通知开关functionisNotificationEnabled():Promiseboolean;functionisNotificationEnabledSync():boolean;同步版本isNotificationEnabledSync()立即返回适合在页面初始化时快速检查constenablednotificationManager.isNotificationEnabledSync();if(!enabled){// 提示用户开启通知权限notificationManager.requestEnableNotification().then((){console.log(已弹出通知权限对话框);});}2.4 getActiveNotifications() —— 获取活跃通知functiongetActiveNotifications():PromiseArrayNotificationRequest;functiongetActiveNotificationCount():Promisenumber;getActiveNotifications()返回当前应用仍在通知栏中展示的所有通知。getActiveNotificationCount()仅返回数量notificationManager.getActiveNotificationCount().then((count:number){this.activeCountcount;});2.5 插槽管理functionaddSlot(type:SlotType):Promisevoid;functiongetSlots():PromiseArrayNotificationSlot;functionremoveSlot(type:SlotType):Promisevoid;插槽必须在发布通知之前创建。如果发布了某个插槽类型的通知但该插槽尚未添加系统会自动创建默认配置的插槽// 添加自定义插槽notificationManager.addSlot(notificationManager.SlotType.CUSTOMER_SERVICE).then((){console.log(客服消息插槽已添加);});// 查询所有插槽notificationManager.getSlots().then((slots){slots.forEach((slot){console.log(插槽类型:,slot.notificationType,级别:,slot.notificationLevel);});});注意NotificationSlot返回的字段中type和level字段来自旧版ohos.notification命名空间已弃用新代码应使用notificationType和notificationLevel字段。2.6 角标管理functionsetBadgeNumber(badgeNumber:number):Promisevoid;functiongetBadgeNumber():Promisenumber;setBadgeNumber()设置桌面应用图标上的角标数字。传入0可清除角标notificationManager.setBadgeNumber(5).then((){console.log(角标已设为 5);});notificationManager.getBadgeNumber().then((num:number){console.log(当前角标数:,num);});三、权限模型3.1 无需权限的操作以下操作在 HarmonyOS 中无需任何权限声明publish()— 发布通知cancel()/cancelAll()— 取消通知isNotificationEnabled()/isNotificationEnabledSync()— 检查通知开关getActiveNotifications()/getActiveNotificationCount()— 查询活跃通知addSlot()/getSlots()/removeSlot()— 插槽管理setBadgeNumber()/getBadgeNumber()— 角标管理这与 Android 的设计形成鲜明对比——在 Android 中从 Android 13API 33开始发布通知需要POST_NOTIFICATIONS运行时权限用户可以选择拒绝。3.2 请求通知权限尽管发布通知不需要权限但如果用户在系统设置中关闭了应用的通知开关publish()会返回错误码 1600004。此时可以使用requestEnableNotification()弹出系统对话框引导用户开启notificationManager.requestEnableNotification().then((){// 用户已做出选择开启或保持关闭constenablednotificationManager.isNotificationEnabledSync();if(enabled){// 用户开启了通知}});四、实战 Demo通知管理实验室本节构建一个完整的通知管理实验室在一个页面中覆盖通知发布、状态查询、插槽管理和操作日志。4.1 页面设计页面分为六个功能区域通知状态面板三栏展示通知开关状态、活跃通知数量、角标数值颜色编码直观显示状态发布通知表单通知标题输入框 正文输入框 5 种 SlotType 可选的插槽选择器 发布按钮快捷操作请求通知权限、设置随机角标、取消全部通知、刷新状态四个按钮通知插槽管理展示所有已添加的插槽包括类型标签、重要等级和描述信息操作日志记录每次操作的完整历史区分系统信息灰色、成功操作绿色、错误红色权限与特性说明两个知识卡片总结 API 能力4.2 核心实现发布通知——构建 NotificationRequest 并调用 publish()privatepublishNotification():void{consttitlethis.titleInput.trim()||通知实验室;constbodythis.bodyInput.trim()||测试通知内容;constrequest:notificationManager.NotificationRequest{id:Date.now(),content:{notificationContentType:notificationManager.ContentType.NOTIFICATION_CONTENT_BASIC_TEXT,normal:{title:title,text:body}},notificationSlotType:this.selectedSlot};notificationManager.publish(request).then((){this.addLog(已发布通知: title,success);this.getActiveCount();}).catch((e:Error){this.addLog(发布失败: e.message,error);});}插槽查询——处理新旧两套字段的兼容性privategetSlots():void{notificationManager.getSlots().then((slotList){constresult:NotifSlot[][];for(leti0;islotList.length;i){constsslotList[i];// 优先使用新版字段 notificationType/notificationLevelconststs.notificationType!undefined?s.notificationType:(s.type!undefined?s.type:0);constsls.notificationLevel!undefined?s.notificationLevel:(s.level!undefined?s.level:2);result.push({type:Number(st),label:this.slotTypeLabel(Number(st)),level:Number(sl),desc:s.desc||});}this.slotsresult;});}这里的关键技巧是优先使用notificationType和notificationLevel字段新版 API并回退到type和level字段旧版兼容。角标设置——随机生成 1-10 的数字并设置privatesetBadge():void{constnumMath.floor(Math.random()*10)1;notificationManager.setBadgeNumber(num).then((){this.badgeNumbernum.toString();this.addLog(角标已设为 num,success);});}4.3 交互方式Demo 提供四个核心交互点发布通知在表单中输入标题和正文从 5 种插槽类型中选择一种社交通信、服务信息、内容资讯、客服消息、实况窗点击发布通知按钮。通知会立即出现在系统通知栏中活跃通知计数同步更新。快捷操作四个快捷按钮覆盖常见操作——请求通知权限会弹出系统对话框设置角标会随机设置桌面角标数字取消全部通知清除所有已发布通知刷新状态重新查询全部数据。插槽查看插槽管理区域展示系统中已添加的通知插槽包括类型标签带彩色圆形指示器、重要等级和描述。开发者可以直观地看到通知分类的全貌。状态追踪顶部的三栏状态面板实时反映通知开关状态绿色已开启或红色已关闭、活跃通知数量和角标数值所有操作历史记录在底部日志中。五、ohos.notification 与 ohos.notificationManager 的关系HarmonyOS 通知系统中存在两个相关的命名空间理解它们的关系对避免类型错误至关重要维度ohos.notificationohos.notificationManager定位旧版通知 API逐步弃用新版通知 API推荐使用SlotType不含 LIVE_VIEW完整 7 种类型通知发布部分方法已废弃publish()为主要接口推荐使用仅用于类型兼容新项目首选在编写代码时应统一使用ohos.notificationManager的SlotType和ContentType。但如果遇到从getSlots()返回的NotificationSlot对象其type字段可能来自旧版命名空间——此时需要做类型转换优先读取notificationType字段。六、ArkTS 严格模式注意事项6.1 保留名称ArkTS 中某些名称是保留的不能用作Component中的属性名。例如activeCount会导致编译错误“Methods, properties and accessors in structures decorated by ‘Component’ cannot have name as ‘activeCount’”。应改用notifCount等替代名称。6.2 跨模块类型不兼容notification.SlotType和notificationManager.SlotType是两个不同的类型即使数值相同也不能互相赋值。解决方法是使用number类型作为中间表示// 正确使用 number 作为中间类型constst:numberNumber(s.notificationType??s.type??0);this.slotTypeLabel(st);// 错误直接使用 notificationManager.SlotType 接收 notification.SlotTypeconstst:notificationManager.SlotTypes.type;// 类型错误6.3 NotificationRequest 字段选择构建通知请求时应使用notificationSlotType而非slotType// 正确使用新版字段constreq{notificationSlotType:notificationManager.SlotType.SOCIAL_COMMUNICATION,...};// 错误slotType 接受 notification.SlotType与 notificationManager.SlotType 不兼容constreq{slotType:notificationManager.SlotType.SOCIAL_COMMUNICATION,...};七、实际应用场景7.1 聊天消息通知privatesendMessageNotification(sender:string,message:string):void{notificationManager.publish({id:Date.now(),content:{notificationContentType:notificationManager.ContentType.NOTIFICATION_CONTENT_BASIC_TEXT,normal:{title:sender,text:message}},notificationSlotType:notificationManager.SlotType.SOCIAL_COMMUNICATION}).catch((e:Error){// 通知被关闭时降级为应用内提示this.showInAppToast(sender: message);});}7.2 下载完成通知privatenotifyDownloadComplete(fileName:string):void{notificationManager.publish({id:1001,content:{notificationContentType:notificationManager.ContentType.NOTIFICATION_CONTENT_BASIC_TEXT,normal:{title:下载完成,text:fileName 已下载完毕}},notificationSlotType:notificationManager.SlotType.SERVICE_INFORMATION});}7.3 角标同步未读消息privatesyncUnreadBadge(unreadCount:number):void{if(unreadCount0){notificationManager.setBadgeNumber(unreadCount);}else{notificationManager.setBadgeNumber(0);}}八、总结ohos.notificationManager是 HarmonyOS NEXT 中通知管理的核心模块。通过本文的学习你应该已经掌握通知发布publish(request)无需权限构建NotificationRequest最少只需 id content notificationSlotType 三个字段内容类型ContentType枚举支持基本文本、长文本、多行、图片等多种通知展现形式插槽分类SlotType定义了 7 种通知分类每种有自己的默认重要等级LOW/DEFAULT/HIGH决定通知的展示行为状态查询isNotificationEnabledSync()同步检查开关getActiveNotifications()查询活跃通知列表角标控制setBadgeNumber()/getBadgeNumber()管理桌面角标类型兼容注意ohos.notification与ohos.notificationManager的类型差异统一使用新版 APIohos.notificationManager的最佳使用模式可以总结为先检查开关再创建插槽然后发布通知适时清理用角标引导用户回归。通知是应用最直接的触达用户方式但滥用通知会导致用户关闭通知权限。合理使用通知插槽分类、尊重用户的通知偏好、在合适的时机发送有价值的内容——这些是优秀的通知策略的核心原则。将通知管理作为应用体验的有机组成部分而非简单的消息推送通道。ohos.notificationManager属于kit.NotificationKit与 Android 的 NotificationManager 和 iOS 的 UNUserNotificationCenter 定位类似但在权限模型上更加开放——发布通知无需权限的设计大大降低了接入门槛。同时插槽机制提供了一套系统级的通知分类框架让用户可以精细地控制每种类型通知的展示行为。

本周精选

本月热点