HarmonyOS 5.0.0 或以上:实现系统原生通知(Notification)推送与提醒交互实战

一、功能简介

本篇讲解如何在 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。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值