一、功能简介
本篇讲解如何在 HarmonyOS 中使用**原生通知系统(Notification)**实现提醒推送,包括定时提醒、点击跳转、图标展示等,适用于系统级任务通知、AI 提醒助手、消息系统等场景。
二、功能目标
-
在指定时间弹出系统级通知;
-
支持通知标题、副标题、内容、图标;
-
点击通知跳转指定页面或触发事件。
三、核心模块
模块 | 功能 | 使用方式 |
---|---|---|
@ohos.notificationManager | 通知创建与发布 | ✅ |
@ohos.bundle | 获取应用包名 | ✅ |
setTimeout / 后台任务 | 触发定时通知 | ✅(基础版本) |
四、页面结构
entry/src/main/ets/pages/NotificationDemo.ets
五、代码演示(发送通知)
import notificationManager from '@ohos.notificationManager'
import bundleManager from '@ohos.bundle'
@Entry
@Component
struct NotificationDemo {
@State task: string = '喝水'
@State time: string = '15:00'
@State message: string = ''
build() {
Column() {
Text('系统级通知提醒示例')
.fontSize(20)
.margin({ bottom: 16 })
TextInput({ placeholder: '提醒内容', text: this.task, onChange: val => this.task = val })
.margin({ bottom: 12 })
TextInput({ placeholder: '时间(如 15:00)', text: this.time, onChange: val => this.time = val })
.margin({ bottom: 12 })
Button('添加通知提醒')
.onClick(() => this.scheduleNotification())
.margin({ bottom: 20 })
Text(this.message)
.fontSize(14)
.fontColor(Color.Blue)
}
.width('100%')
.padding(20)
}
async scheduleNotification() {
const [h, m] = this.time.split(':').map(v => parseInt(v))
const now = new Date()
const target = new Date()
target.setHours(h, m, 0)
let delay = target.getTime() - now.getTime()
if (delay < 0) delay += 86400000 // 第二天
this.message = `已设置提醒:${this.task}(${this.time})`
setTimeout(() => {
this.sendNotification(this.task)
}, delay)
}
async sendNotification(content: string) {
const appInfo = await bundleManager.getBundleInfoForSelf()
const request: notificationManager.NotificationRequest = {
id: Math.floor(Math.random() * 10000),
content: {
contentType: notificationManager.ContentType.NOTIFICATION_CONTENT_BASIC_TEXT,
normal: {
title: '🔔 AI 提醒助手',
text: content,
additionalText: '点击查看任务'
}
},
label: 'task_reminder',
slotType: notificationManager.SlotType.SOCIAL_COMMUNICATION,
deliveryTime: new Date().getTime(),
bundleName: appInfo.name
}
await notificationManager.publish(request)
}
}
六、运行效果
-
输入“提醒内容 + 时间”点击添加;
-
到达指定时间后,系统顶部弹出通知;
-
通知样式为原生系统风格,点击可定制后续跳转行为。
七、常见问题与解决方法
问题 | 表现 | 原因 | 解决方法 |
---|---|---|---|
通知不显示 | 页面成功但无弹窗 | 权限未开启 | 进入应用设置开启通知权限 |
通知没有图标/跳转 | 展示信息不足 | 缺少字段或未绑定动作 | 设置 .label , .bundleName , .additionalText |
setTimeout 无效 | 页面切后台后失效 | 非后台保活 | 正式版本中请使用 backgroundTaskManager 或系统 alarm 接口 |
八、拓展建议
-
使用系统提供的NotificationSlot 配置通道(重要性/声音/横幅样式);
-
增加点击通知后跳转页面或打开任务详情;
-
接入语音提醒、图标通知、进度条更新等丰富 UI。