1. 鸿蒙应用通知机制概述
在鸿蒙生态中,通知系统扮演着连接应用与用户的关键角色。与Android的NotificationManager不同,鸿蒙通过分布式通知服务实现跨设备消息传递。其核心架构包含三个层级:
- 应用层:开发者通过
NotificationRequest构建通知内容 - 框架层:
NotificationHelper负责通知的发布与管理 - 服务层:分布式调度模块实现设备间的通知同步
典型应用场景包括:
- 即时通讯消息提醒
- 后台任务完成通知
- 系统事件预警(如存储空间不足)
- 跨设备操作反馈
注意:鸿蒙通知默认显示在设备通知中心,但不会自动出现在状态栏,需要显式设置
tapDismissed属性
2. 基础通知实现步骤
2.1 配置权限与依赖
在config.json中添加权限声明:
{ "module": { "reqPermissions": [ { "name": "ohos.permission.NOTIFICATION_CONTROLLER", "reason": "推送通知所需权限" } ] } }2.2 构建通知内容
完整通知示例代码:
import notification from '@ohos.notification'; // 创建NotificationRequest对象 let notificationRequest: notification.NotificationRequest = { content: { contentType: notification.ContentType.NOTIFICATION_CONTENT_BASIC_TEXT, normal: { title: "文件下载完成", text: "年度报告.pdf已保存到下载目录", additionalText: "点击查看" } }, id: 1, slotType: notification.SlotType.SOCIAL_COMMUNICATION }; // 添加操作按钮 notificationRequest.actionButtons = [ { title: "打开", wantAgent: { pkgName: "com.example.myapp", abilityName: "MainAbility" } }, { title: "删除", wantAgent: { pkgName: "com.example.myapp", abilityName: "DeleteAbility" } } ]; // 发布通知 notification.publish(notificationRequest).then(() => { console.log("通知发布成功"); });2.3 通知渠道管理
鸿蒙通过Slot管理通知分类,建议为不同类型通知创建独立渠道:
let slot: notification.NotificationSlot = { type: notification.SlotType.SOCIAL_COMMUNICATION, level: notification.SlotLevel.LEVEL_HIGH, sound: "system://media/notifications/ringtone001.mp3", vibrationEnabled: true }; notification.addSlot(slot).then(() => { console.log("通知渠道创建成功"); });3. 高级通知功能实现
3.1 进度条通知
适用于下载、上传等场景:
let progressNotification: notification.NotificationRequest = { id: 2, slotType: notification.SlotType.SERVICE_REMINDER, content: { contentType: notification.ContentType.NOTIFICATION_CONTENT_PROGRESS, progress: { max: 100, value: 0, progressStatus: "正在下载..." } } }; // 模拟进度更新 let currentProgress = 0; let interval = setInterval(() => { currentProgress += 10; progressNotification.content.progress.value = currentProgress; if(currentProgress >= 100) { progressNotification.content.progress.progressStatus = "下载完成"; clearInterval(interval); } notification.publish(progressNotification); }, 1000);3.2 多行文本通知
超过3行内容会自动折叠:
let longTextNotification = { // ...其他参数 content: { contentType: notification.ContentType.NOTIFICATION_CONTENT_LONG_TEXT, longText: { title: "系统安全报告", text: "1. 检测到3个高危漏洞\n2. 发现2个异常登录\n3. 建议立即更新系统补丁\n4. 已自动拦截可疑请求", briefText: "安全警告:发现多个安全隐患", expandedTitle: "详细安全分析" } } };3.3 通知行为控制
// 设置通知时效性 notificationRequest.deliveryTime = new Date().getTime() + 3600000; // 1小时后失效 // 锁屏显示控制 notificationRequest.visibleness = notification.VisiblenessType.VISIBLENESS_PUBLIC; // 设置勿扰模式下的行为 notificationRequest.tapDismissed = true; // 点击后消失 notificationRequest.autoDeletedTime = 5000; // 5秒后自动消失4. 分布式通知实战
4.1 跨设备通知同步
import distributedNotification from '@ohos.distributedNotification'; let distributedRequest = { // ...基础通知参数 isDistributed: true, devices: ["1234567890"] // 目标设备ID数组 }; distributedNotification.publish(distributedRequest).then(() => { console.log("分布式通知发送成功"); });4.2 通知同步策略配置
在config.json中声明分布式能力:
{ "deviceTypes": ["phone", "tablet", "tv"], "distributedNotificationEnabled": true }4.3 接收其他设备通知
distributedNotification.subscribe({ onReceive: (data) => { console.log("收到来自" + data.deviceId + "的通知:" + JSON.stringify(data)); } });5. 调试与性能优化
5.1 常见问题排查
通知不显示检查清单:
- 确认权限已正确声明
- 检查
SlotType是否匹配 - 验证
WantAgent配置是否正确 - 查看系统通知开关状态
- 检查勿扰模式是否开启
5.2 性能优化建议
- 批量更新:避免高频单次更新,推荐合并更新
- 资源复用:对静态内容使用
NotificationTemplate - 优先级控制:合理使用
LEVEL_HIGH/LEVEL_DEFAULT - 内存管理:及时取消不再需要的通知
// 使用模板示例 let template = { name: "download_template", data: { title: "下载进度", progress: "{progress}%" } }; notification.addTemplate(template).then(() => { console.log("模板添加成功"); });6. 实际项目中的经验技巧
- 设备兼容处理:
function isWatchDevice() { try { return deviceInfo.deviceType === 'watch'; } catch (e) { return false; } } if (isWatchDevice()) { // 智能手表需要简化通知内容 notificationRequest.content.normal.text = notificationRequest.content.normal.text.substring(0, 20) + "..."; }- 动态图标技巧:
// 根据状态切换图标 function getStatusIcon(status) { const icons = { success: "resource://media/ic_success.png", error: "resource://media/ic_error.png", progress: "resource://media/ic_loading.gif" }; return icons[status] || icons.progress; } notificationRequest.smallIcon = getStatusIcon('progress');- 通知分组最佳实践:
// 对聊天类应用按会话分组 let groupNotification = { groupName: "chat_group", groupOverview: "3条新消息", // ...其他参数 };- 本地化字符串处理:
// 使用资源引用替代硬编码 notificationRequest.content.normal = { title: $r('app.strings.notification_title'), text: $r('app.strings.notification_text') };