一、背景说明

本地通知是应用触达用户的标准通道:下载完成提醒、消息推送落地、进度更新都依赖它。HarmonyOS 7 生态里通知体验持续升级(26.0.0 Release 起通知管理能力增强、支持以半模态方式拉起应用的通知设置界面;WATCH GT7 新版进一步扩展实况窗与通知场景),应用侧的开发入口是 Notification Kit 的 notificationManager。本文以"下载进度通知"为主线,完整实现"通知授权 → 发布文本/多行/进度条三类通知 → 同 ID 更新 → 取消"全流程,代码基于 API 9 及以上(含 26.0.x),可直接运行。

二、技术原理

Notification Kit 提供本地通知发布通道,核心对象与流程:

  1. 授权前置:应用通知用户的能力默认关闭,发布前需调用 requestEnableNotification() 拉起授权框请求用户授权;
  2. NotificationRequest:通知请求对象,id 是通知的唯一标识(同 id 发布即更新内容,配合 updateOnly: true 表示只更新不新建);content.notificationContentType 决定通知类型(普通文本、多行文本、图片、进度条等),不同类型对应不同的内容字段;
  3. 进度条模板:进度条通知通过模板机制实现——isSupportTemplate('downloadTemplate') 查询系统支持性,template.name 固定为 downloadTemplate,template.data 携带文件名与进度值;
  4. 频次限制:单应用发布新通知不超过每秒 10 条、更新不超过每秒 20 条(全系统三方应用累计为每秒 15/30 条),超限返回错误码,进度更新应按实际节奏控制。
三、实现步骤

1. 通知封装类 entry/src/main/ets/notification/NotificationHelper.ets(完整代码):

import { notificationManager } from '@kit.NotificationKit';
import { BusinessError } from '@kit.BasicServicesKit';
import { hilog } from '@kit.PerformanceAnalysisKit';

const TAG: string = 'NotificationHelper';

export class NotificationHelper {
  // 请求通知授权,用户同意后才能发布
  async requestPermission(): Promise<boolean> {
    try {
      await notificationManager.requestEnableNotification();
      return true;
    } catch (err) {
      const e: BusinessError = err as BusinessError;
      hilog.error(TAG, 'notification denied: %{public}d', e.code);
      return false;
    }
  }

  // 发布普通文本通知
  async publishBasic(): Promise<void> {
    const request: notificationManager.NotificationRequest = {
      id: 1,
      content: {
        notificationContentType:
          notificationManager.ContentType.NOTIFICATION_CONTENT_BASIC_TEXT,
        normal: {
          title: '下载提醒',
          text: '您选择的文件已加入下载队列',
          additionalText: 'Download Demo'
        }
      }
    };
    await notificationManager.publish(request);
    hilog.info(TAG, 'basic published');
  }

  // 发布多行文本通知
  async publishMultiLine(): Promise<void> {
    const request: notificationManager.NotificationRequest = {
      id: 2,
      content: {
        notificationContentType:
          notificationManager.ContentType.NOTIFICATION_CONTENT_MULTILINE,
        multiLine: {
          title: '下载列表',
          text: '3 个文件正在排队',
          briefText: 'Download Demo',
          longTitle: '批量下载',
          lines: ['music.mp4', 'photo.jpg', 'video.mp4']
        }
      }
    };
    await notificationManager.publish(request);
    hilog.info(TAG, 'multiline published');
  }

  // 查询系统是否支持进度条模板
  async supportProgressTemplate(): Promise<boolean> {
    try {
      const data: boolean =
        await notificationManager.isSupportTemplate('downloadTemplate');
      return data;
    } catch (err) {
      const e: BusinessError = err as BusinessError;
      hilog.error(TAG, 'isSupportTemplate failed: %{public}d', e.code);
      return false;
    }
  }

  // 发布/更新进度条通知:id 固定为 5,更新时 updateOnly=true
  async publishProgress(progressValue: number, updateOnly: boolean): Promise<void> {
    const request: notificationManager.NotificationRequest = {
      id: 5,
      updateOnly: updateOnly,
      content: {
        notificationContentType:
          notificationManager.ContentType.NOTIFICATION_CONTENT_BASIC_TEXT,
        normal: {
          title: '下载中',
          text: `已完成 ${progressValue}%`,
          additionalText: 'Download Demo'
        }
      },
      // 进度条模板:name 固定为 downloadTemplate
      template: {
        name: 'downloadTemplate',
        data: { progressValue: progressValue }
      }
    };
    await notificationManager.publish(request);
    hilog.info(TAG, 'progress published: %{public}d', progressValue);
  }

  // 取消指定通知
  async cancel(id: number): Promise<void> {
    await notificationManager.cancel(id);
    hilog.info(TAG, 'notification %{public}d cancelled', id);
  }
}
四、应用场景示例

在 Index.ets 中演示三类通知的发布与进度条更新:

import { NotificationHelper } from '../notification/NotificationHelper';

@Entry
@Component
struct Index {
  private helper: NotificationHelper = new NotificationHelper();
  @State log: string = '就绪';

  build() {
    Column({ space: 10 }) {
      Text(this.log).fontSize(14)
      Button('请求通知授权').onClick(async () => {
        const ok = await this.helper.requestPermission();
        this.log = ok ? '通知已授权' : '授权被拒绝';
      })
      Button('普通文本通知').onClick(() => {
        this.helper.publishBasic();
      })
      Button('多行文本通知').onClick(() => {
        this.helper.publishMultiLine();
      })
      Button('发布进度条通知').onClick(async () => {
        if (await this.helper.supportProgressTemplate()) {
          await this.helper.publishProgress(45, false);
        }
      })
      Button('更新进度到 99%').onClick(async () => {
        // 相同 id + updateOnly=true 表示只更新不新建
        await this.helper.publishProgress(99, true);
      })
      Button('取消进度通知').onClick(async () => {
        await this.helper.cancel(5);
        this.log = '进度通知已取消';
      })
    }
    .width('100%').height('100%').justifyContent(FlexAlign.Center)
  }
}
五、技术要点
  1. 授权前置:requestEnableNotification() 只会弹一次授权框,用户拒绝后再次调用不再弹窗,需引导用户去系统设置手动开启,再配合 isNotificationEnabled() 查询实际状态;
  2. 同 id 更新:通知更新通过"相同 id + updateOnly: true"实现,不传 updateOnly 时会新建一条通知;进度条更新必须走这条路,否则每秒刷新会瞬间刷满通知栏;
  3. 频次红线:单应用新发布 ≤10 条/秒、更新 ≤20 条/秒(全系统三方累计 15/30 条/秒),下载类应用应把进度刷新间隔控制在合理节奏(如每秒 1~2 次),而不是每个字节都发;
  4. 模板先查询再使用:进度条通知依赖 downloadTemplate 模板,用 isSupportTemplate() 先查询,不支持的平台要降级为纯文本通知;
  5. 内容规格:通知正文最多显示三行,多行类型每行超长以"…"截断;标题、正文、附加文本都支持本地化资源引用。
六、扩展建议

需要用户点击通知跳转到指定页面时,为 NotificationRequest 配置 wantAgent(通过 @kit.AbilityKit 的 wantAgent.getWantAgent 构造),即可实现"点击通知直达详情页";对需要长时间运行的任务,把进度条通知与 Background Tasks Kit 的长时任务结合使用(26.0.1 起数据传输型长时任务已内置进度模板);音视频、多设备流转等更多通知类型可按需扩展。

结语

本文用约 120 行 ArkTS 完成了本地通知从授权、三类内容发布到同 id 更新与取消的完整实战,核心是 NotificationRequest 的 contentType 路由与 downloadTemplate 进度模板。掌握授权前置、同 id 更新与频次控制三点,即可为应用构建规范且用户友好的通知体系。

代码仓库

本文完整示例工程已在 AtomGit 开源,为标准鸿蒙 Stage 工程(AppScope 应用配置、entry 模块、NotificationHelper 封装与页面、hvigor 构建脚本齐全),DevEco Studio 可直接打开编译运行:https://atomgit.com/NJPJI_Yang/hm-article-2026-11-26-notification-kit-notification-kit-atomgit

Logo

讨论HarmonyOS开发技术,专注于API与组件、DevEco Studio、测试、元服务和应用上架分发等。

更多推荐