鸿蒙三方库 | harmony-utils之NotificationUtil图片通知与模板通知详解
前言图片通知可以在通知中展示图片缩略图适用于聊天图片、商品推荐等场景。模板通知则提供了更多自定义布局选项。pura/harmony-utils的NotificationUtil封装了图片通知发送方法。本文将从API说明、代码实战、进阶用法、常见问题等多个维度进行全面讲解帮助开发者快速掌握并应用到实际项目中。一、NotificationUtil图片核心APINotificationUtil提供了以下图片通知方法方法说明参数使用场景publishWithImage(title, text, pixelMap)发送图片通知title, text, pixelMap图片消息publishTemplate(title, text, template)发送模板通知title, text, template自定义布局1.1 核心特性简洁易用封装复杂API为一行调用降低使用门槛类型安全完整的TypeScript类型定义编译期即可发现错误异常处理内置异常捕获机制避免运行时崩溃图片支持支持在通知中展示图片缩略图1.2 通知样式对照样式方法展示内容适用场景基本通知publish文本简短消息图片通知publishWithImage文本图片图片消息模板通知publishTemplate自定义布局下载进度二、完整使用步骤2.1 安装依赖ohpminstallpura/harmony-utils2.2 发送图片通知import{NotificationUtil}frompura/harmony-utils;Button(发送图片通知).width(100%).onClick(async(){try{letpixelMapawaitthis.loadPixelMap();NotificationUtil.publishWithImage(图片消息,收到一张图片,pixelMap);this.result图片通知已发送 ️;}catch(e){this.result异常: e;}})2.3 发送模板通知Button(发送模板通知).width(100%).onClick((){try{NotificationUtil.publishTemplate(下载通知,文件下载中,download);this.result模板通知已发送 ;}catch(e){this.result异常: e;}})三、完整页面示例import{NotificationUtil}frompura/harmony-utils;EntryComponentstruct NotifImageDemo{Stateresult:string;build(){Column({space:12}){Button(图片通知).width(100%).onClick(async(){try{NotificationUtil.publishWithImage(图片,收到图片,this.pixelMap);this.result已发送;}catch(e){this.result异常: e;}});Text(this.result).fontSize(14).fontColor(#333333)}.padding(16)}}四、进阶用法4.1 商品推荐通知import{NotificationUtil}frompura/harmony-utils;asyncfunctionsendProductNotification(product:Product):Promisevoid{letpixelMapawaitImageUtil.base64ToPixelMap(product.imageBase64);NotificationUtil.publishWithImage(product.name,product.price,pixelMap);}4.2 下载进度通知functionupdateDownloadNotification(progress:number):void{NotificationUtil.publishTemplate(下载中,进度:${progress}%,download);}五、注意事项图片大小通知图片不宜过大建议缩略图PixelMap需要先创建PixelMap对象权限要求发送通知需要通知权限初始化依赖使用前需确保AppUtil.init()已调用模板类型模板通知的具体样式取决于系统支持六、常见问题Q1: 图片通知显示不出图片检查PixelMap是否有效图片是否过大。Q2: 模板通知有哪些可用模板具体可用模板取决于系统版本常见有下载进度、社交消息等。Q3: 图片通知可以点击查看大图吗基本图片通知不支持点击查看大图需要配置WantAgent实现。Q4: 如何更新图片通知的内容使用publishWithId配合相同ID可以更新通知内容和图片。总结NotificationUtil的图片通知和模板通知方法为丰富通知展示提供了支持。本文详细介绍了核心API、使用步骤、完整示例、进阶用法以及常见问题的解决方案。开发者可以根据场景选择合适的通知样式。本文基于pura/harmony-utils工具库更多功能请参考官方文档与后续系列文章。