鸿蒙三方库 | harmony-utils之NotificationUtil基本通知发送详解

发布时间:2026/7/23 18:01:17
鸿蒙三方库 | harmony-utils之NotificationUtil基本通知发送详解 前言通知是应用与用户沟通的重要渠道用于消息提醒、进度展示等。pura/harmony-utils的NotificationUtil封装了通知发送方法支持基本文本通知。本文将从API说明、代码实战、进阶用法、常见问题等多个维度进行全面讲解帮助开发者快速掌握并应用到实际项目中。一、NotificationUtil基本核心APINotificationUtil提供了以下基本通知方法方法说明返回类型使用场景publish(title, text)发送基本通知void消息提醒publishWithId(id, title, text)发送带ID通知void可更新通知cancel(id)取消通知void清除通知cancelAll()取消全部通知void全量清除1.1 核心特性简洁易用封装复杂API为一行调用降低使用门槛类型安全完整的TypeScript类型定义编译期即可发现错误异常处理内置异常捕获机制避免运行时崩溃ID管理支持通知ID可更新和取消特定通知1.2 通知类型对照类型方法特点适用场景基本通知publish简单文本普通消息带ID通知publishWithId可更新/取消下载进度二、完整使用步骤2.1 安装依赖ohpminstallpura/harmony-utils2.2 发送基本通知import{NotificationUtil}frompura/harmony-utils;Button(发送基本通知).width(100%).onClick((){try{NotificationUtil.publish(新消息,您有一条未读消息);this.result通知已发送 ;}catch(e){this.result异常: e;}})2.3 发送带ID通知Button(发送带ID通知).width(100%).onClick((){try{NotificationUtil.publishWithId(1001,下载通知,文件下载中...);this.result通知已发送 \nID: 1001\n可用于后续更新或取消;}catch(e){this.result异常: e;}})2.4 取消通知Button(取消通知).width(100%).onClick((){try{NotificationUtil.cancel(1001);this.result通知已取消 ✅;}catch(e){this.result异常: e;}})三、完整页面示例import{NotificationUtil}frompura/harmony-utils;EntryComponentstruct NotifBasicDemo{Stateresult:string;build(){Column({space:12}){Button(发送通知).width(100%).onClick((){try{NotificationUtil.publish(提示,操作完成);this.result通知已发送;}catch(e){this.result异常: e;}});Button(取消全部).width(100%).onClick((){NotificationUtil.cancelAll();this.result已取消全部通知;});Text(this.result).fontSize(14).fontColor(#333333)}.padding(16)}}四、进阶用法4.1 下载进度通知import{NotificationUtil}frompura/harmony-utils;constDOWNLOAD_NOTIF_ID2001;functionupdateDownloadProgress(progress:number):void{NotificationUtil.publishWithId(DOWNLOAD_NOTIF_ID,下载中,进度:${progress}%);}functionfinishDownload():void{NotificationUtil.publishWithId(DOWNLOAD_NOTIF_ID,下载完成,文件已保存);}4.2 通知管理器classNotificationManager{privatestaticcounter3000;staticsend(title:string,text:string):number{letidNotificationManager.counter;NotificationUtil.publishWithId(id,title,text);returnid;}staticcancelById(id:number):void{NotificationUtil.cancel(id);}}五、注意事项权限要求发送通知需要通知权限通知渠道部分系统需要创建通知渠道频率限制避免短时间内发送大量通知初始化依赖使用前需确保AppUtil.init()已调用用户设置用户可能关闭应用通知六、常见问题Q1: 通知发送后看不到检查通知权限是否已授予以及系统通知设置是否开启。Q2: 带ID通知如何更新使用相同ID再次调用publishWithId即可更新通知内容。Q3: cancel()和cancelAll()有什么区别cancel()取消指定ID的通知cancelAll()取消所有通知。Q4: 通知可以点击跳转吗基本通知不支持点击跳转需要使用WantAgent配置点击行为。总结NotificationUtil的基本通知方法为应用消息提醒提供了便捷支持。本文详细介绍了核心API、使用步骤、完整示例、进阶用法以及常见问题的解决方案。开发者可以利用通知功能及时向用户传递重要信息。本文基于pura/harmony-utils工具库更多功能请参考官方文档与后续系列文章。