鸿蒙三方库 | harmony-utils之NotificationUtil长文本与多行通知详解
·
前言
当通知内容较多时,基本通知的显示空间有限。HarmonyOS支持长文本和多行通知样式,可以展示更多内容。@pura/harmony-utils 的 NotificationUtil 封装了长文本通知发送方法。本文将从API说明、代码实战、进阶用法、常见问题等多个维度进行全面讲解,帮助开发者快速掌握并应用到实际项目中。

一、NotificationUtil长文本核心API
NotificationUtil 提供了以下长文本通知方法:
| 方法 | 说明 | 参数 | 使用场景 |
|---|---|---|---|
publishLongText(title, text, longText) |
发送长文本通知 | title, text, longText | 详细消息 |
publishMultiLine(title, text, lines) |
发送多行通知 | title, text, lines | 消息列表 |
1.1 核心特性
- 简洁易用:封装复杂API为一行调用,降低使用门槛
- 类型安全:完整的TypeScript类型定义,编译期即可发现错误
- 异常处理:内置异常捕获机制,避免运行时崩溃
- 丰富内容:支持长文本和多行两种扩展样式
1.2 通知样式对照
| 样式 | 方法 | 展示方式 | 适用场景 |
|---|---|---|---|
| 基本通知 | publish | 单行文本 | 简短消息 |
| 长文本 | publishLongText | 展开查看全文 | 详细描述 |
| 多行 | publishMultiLine | 多行列表 | 消息汇总 |
二、完整使用步骤
2.1 安装依赖
ohpm install @pura/harmony-utils
2.2 发送长文本通知
import { NotificationUtil } from '@pura/harmony-utils';
Button('发送长文本通知')
.width('100%')
.onClick(() => {
try {
let longText = '这是一段很长的通知内容,包含详细的描述信息。展开通知可以查看完整内容。适用于需要展示详细信息的场景。';
NotificationUtil.publishLongText('长文本通知', '摘要', longText);
this.result = '长文本通知已发送 📜\n展开可查看完整内容';
} catch (e) {
this.result = '异常: ' + e;
}
})
2.3 发送多行通知
Button('发送多行通知')
.width('100%')
.onClick(() => {
try {
let lines = ['第1条消息', '第2条消息', '第3条消息'];
NotificationUtil.publishMultiLine('多行通知', '3条新消息', lines);
this.result = '多行通知已发送 📋\n共3行内容';
} catch (e) {
this.result = '异常: ' + e;
}
})

三、完整页面示例
import { NotificationUtil } from '@pura/harmony-utils';
@Entry
@Component
struct NotifLongDemo {
@State result: string = '';
build() {
Column({ space: 12 }) {
Button('长文本通知').width('100%').onClick(() => {
try {
NotificationUtil.publishLongText('通知', '摘要', '详细内容...');
this.result = '已发送';
} catch (e) { this.result = '异常: ' + e; }
});
Button('多行通知').width('100%').onClick(() => {
try {
NotificationUtil.publishMultiLine('消息', '新消息', ['消息1', '消息2']);
this.result = '已发送';
} catch (e) { this.result = '异常: ' + e; }
});
Text(this.result).fontSize(14).fontColor('#333333')
}
.padding(16)
}
}
四、进阶用法
4.1 邮件通知
import { NotificationUtil } from '@pura/harmony-utils';
function sendEmailNotification(subject: string, preview: string, body: string): void {
NotificationUtil.publishLongText(subject, preview, body);
}
4.2 聊天消息汇总
function sendChatSummary(messages: string[]): void {
NotificationUtil.publishMultiLine('聊天消息', `${messages.length}条新消息`, messages);
}
五、注意事项
- 内容长度:长文本通知展开后显示,注意内容长度
- 行数限制:多行通知建议不超过5行
- 权限要求:发送通知需要通知权限
- 初始化依赖:使用前需确保
AppUtil.init()已调用 - 兼容性:部分旧系统可能不支持长文本样式
六、常见问题
Q1: 长文本通知只显示摘要?
需要展开通知才能看到完整内容,这是系统通知的默认行为。
Q2: 多行通知最多显示几行?
通常显示3-5行,超出部分会被截断。
Q3: 长文本和多行可以同时使用吗?
不可以,一条通知只能使用一种样式。
Q4: 如何让通知自动展开?
通知默认折叠,用户需要手动展开,应用无法控制。


总结
NotificationUtil 的长文本和多行通知方法为丰富内容展示提供了支持。本文详细介绍了核心API、使用步骤、完整示例、进阶用法以及常见问题的解决方案。开发者可以根据内容类型选择合适的通知样式。
本文基于
@pura/harmony-utils工具库,更多功能请参考官方文档与后续系列文章。
更多推荐



所有评论(0)