HarmonyOS 通知服务(Notification Kit)开发全指南


1. 概述

1.1 什么是Notification Kit

Notification Kit(通知服务)是鸿蒙系统提供的核心服务框架,为开发者提供本地通知的发布、订阅、管理能力。通过Notification Kit,应用可以将消息以通知的形式推送给用户,通知会以铃声、震动、横幅、锁屏等多种方式提醒用户。

1.2 通知类型分类

通知类型 ContentType常量 说明 适用场景
普通文本通知 NOTIFICATION_CONTENT_BASIC_TEXT 基础文本通知 一般信息推送
长文本通知 NOTIFICATION_CONTENT_LONG_TEXT 可展开的折叠通知 详情内容展示
进度条通知 NOTIFICATION_CONTENT_PROGRESS 带有进度条的通知 文件下载、任务进度
社交类通知 NOTIFICATION_CONTENT_MULTILINE 多行文本通知 聊天记录、引用内容

2. 通知权限管理

2.1 权限管理流程

通知权限管理是通知功能的基础,完整的权限管理流程如下:

┌─────────────────┐
│ 检查通知是否启用   │ ──是──→ 直接使用通知功能
└────────┬────────┘
         │否
         ▼
┌─────────────────┐
│ 请求通知授权     │ ──成功──→ 使用通知功能
└────────┬────────┘
         │失败(用户拒绝)
         ▼
┌─────────────────┐
│ 打开系统设置页面  │ ──用户开启──→ 使用通知功能
└─────────────────┘

2.2 检查通知权限状态

API说明isNotificationEnabled() 用于检查通知功能是否已启用,提供同步 / 异步两种 API,建议在发送通知前统一检查。。

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

const TAG: string = '[NotificationModule]';
const DOMAIN_NUMBER: number = 0xFF00;

/**
 * 检查通知权限是否已启用
 * @returns Promise<boolean> true表示已启用,false表示未启用
 * @description 在发送任何通知前,都应该先检查此状态
 *
 * 使用场景:
 * 1. 应用启动时检查
 * 2. 发送通知前检查
 * 3. 设置页面返回时检查
 */
static async checkNotificationEnabled(): Promise<boolean> {
  try {
    // 调用系统API检查通知状态
    let enabled: boolean = await notificationManager.isNotificationEnabled();
    hilog.info(DOMAIN_NUMBER, TAG, `通知状态: ${enabled}`);
    return enabled;
  } catch (err) {
    // 捕获错误并记录
    let error = err as BusinessError;
    hilog.error(DOMAIN_NUMBER, TAG, `检查通知状态失败: ${error.code}, ${error.message}`);
    return false;
  }
}

同步检查方式

// 同步方式检查通知状态,更高效
let isEnabled: boolean = notificationManager.isNotificationEnabledSync();

2.3 请求通知授权

API说明requestEnableNotification(context) 请求用户授权通知权限,用户拒绝后再次调用不会再弹框。

import { common } from '@kit.AbilityKit';

/**
 * 请求通知授权
 * @param context UIAbility的上下文对象
 * @returns Promise<boolean> true表示授权成功,false表示失败
 *
 * 注意事项:
 * 1. 此方法会弹出系统授权对话框
 * 2. 如果用户之前已拒绝过,可能直接失败
 * 3. 建议先检查状态,再决定是否请求
 */
static async requestNotificationPermission(context: common.UIAbilityContext): Promise<boolean> {
  try {
    // 调用系统API请求通知授权
    await notificationManager.requestEnableNotification(context);
    hilog.info(DOMAIN_NUMBER, TAG, `请求通知授权成功`);

    // 授权成功后再次确认状态
    let enabled = await NotificationUtil.checkNotificationEnabled();
    return enabled;
  } catch (err) {
    let error = err as BusinessError;

    // 错误码1600004表示用户拒绝授权
    if (error.code === 1600004) {
      hilog.warn(DOMAIN_NUMBER, TAG, `用户拒绝通知授权, code: ${error.code}`);
    } else {
      hilog.error(DOMAIN_NUMBER, TAG, `请求通知授权失败: ${error.code}, ${error.message}`);
    }

    return false;
  }
}

2.4 打开通知设置页面

API说明:用户拒绝授权后,引导手动开启是更友好的体验。通过openNotificationSettings(context) 打开系统通知设置页面。

/**
 * 打开通知设置页面
 * @param context UIAbility的上下文对象
 * @returns Promise<void>
 *
 * 使用场景:
 * 1. 用户首次拒绝授权后,引导用户手动开启
 * 2. 提供设置入口,让用户自主管理通知
 * 3. 应用内设置页面跳转
 */
static async openNotificationSettings(context: common.UIAbilityContext): Promise<void> {
  try {
    // 打开系统通知设置页面
    await notificationManager.openNotificationSettings(context);
    hilog.info(DOMAIN_NUMBER, TAG, `打开通知设置页面成功`);
  } catch (err) {
    let error = err as BusinessError;
    hilog.error(DOMAIN_NUMBER, TAG, `打开通知设置页面失败: ${error.code}, ${error.message}`);
  }
}

2.5 项目实际实现

以下是NotificationAuthorizationPopup项目中的完整权限申请实现:

// MainPage.ets 中的权限申请实现

@Entry
@Component
struct MainPage {
  // 标记弹窗是否已显示,避免重复弹窗
  @State isDialogShown: boolean = false;

  // 获取Ability上下文
  context = this.getUIContext().getHostContext() as common.UIAbilityContext;

  /**
   * 页面即将显示时检查通知权限
   * aboutToAppear是页面生命周期回调,在页面显示前调用
   */
  async aboutToAppear() {
    // 同步方式检查通知状态
    if (!notificationManager.isNotificationEnabledSync()) {
      // 第一次请求授权
      await this.requestPermissions();

      // 如果一次授权后仍未成功,进行二次授权(打开设置页面)
      if (this.isDialogShown !== true) {
        await this.requestPermissionsOnSetting();
      }
    }
  }

  /**
   * 第一次权限请求
   * 请求系统弹出授权对话框
   */
  async requestPermissions(): Promise<void> {
    try {
      // 请求通知授权,系统会弹出授权对话框
      await notificationManager.requestEnableNotification(this.context);
      this.isDialogShown = true;
      hilog.info(0x0000, 'testTag', `requestEnableNotification success`);
    } catch (err) {
      hilog.error(0x0000, 'testTag',
        `requestEnableNotification failed, code is ${err.code}, message is ${err.message}`);
    }
  }

  /**
   * 二次授权
   * 当一次授权被拒绝时,打开系统设置页面引导用户手动开启
   */
  async requestPermissionsOnSetting(): Promise<void> {
    try {
      // 打开系统通知设置页面
      await notificationManager.openNotificationSettings(this.context);
      hilog.info(0x0000, 'testTag', `openNotificationSettings success`);
    } catch (err) {
      hilog.error(0x0000, 'testTag',
        `openNotificationSettings failed, code is ${err.code}, message is ${err.message}`);
    }
  }
}

3. 通知渠道管理

3.1 通知渠道类型详解

通知渠道(Slot)用于分类管理不同类型的通知,系统会根据渠道类型应用不同的提醒策略:

SlotType常量 名称 横幅 锁屏 铃声/振动 状态栏图标
UNKNOWN_TYPE 0 未知类型
SOCIAL_COMMUNICATION 1 社交通信
SERVICE_INFORMATION 2 服务提醒
CONTENT_INFORMATION 3 内容资讯
CUSTOMER_SERVICE 5 客服消息
OTHER_TYPES 0xFFFF 其他类型

3.2 创建通知渠道

API说明addSlot(type: SlotType) 创建指定类型的通知渠道。

/**
 * 创建通知渠道
 * @param slotType 通知渠道类型
 * @returns Promise<void>
 *
 * 注意事项:
 * 1. 通知渠道创建是持久化的,创建一次即可
 * 2. 重复创建已存在的渠道会忽略,不会报错
 * 3. 建议在应用启动时创建所有可能用到的渠道
 *
 * 本项目实际用法:
 * 在发布通知时指定notificationSlotType,系统会自动创建
 */
static async createNotificationSlot(slotType: notificationManager.SlotType): Promise<void> {
  try {
    // 创建服务提醒类型的通知渠道
    // 服务提醒适用于:订单状态、预约提醒、进度通知等
    await notificationManager.addSlot(notificationManager.SlotType.SERVICE_INFORMATION);
    hilog.info(DOMAIN_NUMBER, TAG, `创建通知渠道成功: ${slotType}`);
  } catch (err) {
    let error = err as BusinessError;
    // 1600005表示该类型的渠道已存在,无需重复创建
    hilog.warn(DOMAIN_NUMBER, TAG, `创建通知渠道警告: ${error.code}, ${error.message}`);
  }
}

3.3 查询通知渠道

API说明getSlot(slotType: SlotType) 获取指定类型的通知渠道信息。

/**
 * 查询通知渠道详情
 * @param slotType 通知渠道类型
 * @returns Promise<NotificationSlot> 渠道信息对象
 *
 * NotificationSlot包含以下属性:
 * - slotType: 渠道类型
 * - name: 渠道名称
 * - description: 渠道描述
 * - enabled: 渠道是否启用
 * - vibrationEnabled: 震动是否启用
 * - lightEnabled: 呼吸灯是否启用
 * - soundEnabled: 声音是否启用
 */
static async getSlotInfo(slotType: notificationManager.SlotType): Promise<void> {
  try {
    let slot: notificationManager.NotificationSlot =
      await notificationManager.getSlot(slotType);

    hilog.info(DOMAIN_NUMBER, TAG, `查询通知渠道成功`);
    hilog.info(DOMAIN_NUMBER, TAG, `渠道类型: ${slot.slotType}`);
    hilog.info(DOMAIN_NUMBER, TAG, `渠道启用状态: ${slot.enabled}`);
    hilog.info(DOMAIN_NUMBER, TAG, `震动启用状态: ${slot.vibrationEnabled}`);
    hilog.info(DOMAIN_NUMBER, TAG, `呼吸灯启用状态: ${slot.lightEnabled}`);
  } catch (err) {
    let error = err as BusinessError;
    hilog.error(DOMAIN_NUMBER, TAG, `查询通知渠道失败: ${error.code}, ${error.message}`);
  }
}

3.4 获取所有通知渠道

API说明getSlots() 获取应用创建的所有通知渠道。

/**
 * 获取所有通知渠道
 * @returns Promise<NotificationSlot[]> 渠道数组
 */
static async getAllSlots(): Promise<notificationManager.NotificationSlot[]> {
  try {
    let slots: notificationManager.NotificationSlot[] =
      await notificationManager.getSlots();
    hilog.info(DOMAIN_NUMBER, TAG, `获取到 ${slots.length} 个通知渠道`);
    return slots;
  } catch (err) {
    let error = err as BusinessError;
    hilog.error(DOMAIN_NUMBER, TAG, `获取通知渠道失败: ${error.code}, ${error.message}`);
    return [];
  }
}

3.5 删除通知渠道

API说明removeSlot(slotType: SlotType) 删除指定类型的通知渠道。

/**
 * 删除通知渠道
 * @param slotType 通知渠道类型
 * @returns Promise<void>
 *
 * 注意事项:
 * 1. 删除渠道后,该渠道下的所有通知也会被清除
 * 2. 删除后重新发布该类型通知,需要重新创建渠道
 * 3. 建议不要轻易删除渠道,除非确实不需要
 */
static async removeNotificationSlot(slotType: notificationManager.SlotType): Promise<void> {
  try {
    await notificationManager.removeSlot(slotType);
    hilog.info(DOMAIN_NUMBER, TAG, `删除通知渠道成功: ${slotType}`);
  } catch (err) {
    let error = err as BusinessError;
    hilog.error(DOMAIN_NUMBER, TAG, `删除通知渠道失败: ${error.code}, ${error.message}`);
  }
}

4. 通知发布、更新、取消

4.1 NotificationRequest核心属性

发布通知的核心是构建NotificationRequest对象,以下是主要属性:

let request: notificationManager.NotificationRequest = {
  // ========== 必需属性 ==========

  // 通知ID:用于唯一标识一条通知,更新通知时使用相同ID
  id: 1001,

  // 通知内容:定义通知的显示内容
  content: {
    // 通知内容类型
    notificationContentType: notificationManager.ContentType.NOTIFICATION_CONTENT_BASIC_TEXT,
    // 普通文本通知内容
    normal: {
      title: "通知标题",        // 必填,通知标题
      text: "通知正文",         // 必填,通知正文
      additionalText: "附加信息" // 可选,附加描述
    }
  },

  // ========== 可选属性 ==========

  // 通知标签:用于分组管理通知,取消通知时可指定标签
  label: "工作提醒",

  // 通知渠道类型:指定通知所属的渠道
  // 如果该渠道不存在,系统会自动创建
  notificationSlotType: notificationManager.SlotType.SERVICE_INFORMATION,

  // 通知图标:使用layered-image分层图片
  icon: $r('media.layered_image'),

  // 提示图标:横幅通知时显示的图标
  bannerImage: $r('media.banner'),

  // 排序信息:用于通知列表中的排序
  sortNumber: 100,

  // 发布时间:Unix时间戳(毫秒),默认为当前时间
  deliveryTime: Date.now(),

  // 点击通知后是否移除通知
  removalWantAgent: {
    uri: ""
  },

  // 通知的Want信息:点击通知后拉起的Ability
  want: {
    moduleName: "entry",
    bundleName: "com.example.notificationauthorizationpopup",
    abilityName: "EntryAbility"
  }
};

4.2 普通文本通知发布

普通文本通知是最基础的通知类型,适用于大多数场景:

/**
 * 发布普通文本通知
 * @param title 通知标题
 * @param content 通知内容
 * @param slotType 通知渠道类型
 * @returns Promise<number> 返回通知ID
 *
 * 本项目实际应用场景:
 * - 职位申请成功通知
 * - 面试邀请通知
 * - HR消息通知
 */
static async publishBasicNotification(
  title: string,
  content: string,
  slotType: notificationManager.SlotType = notificationManager.SlotType.SOCIAL_COMMUNICATION
): Promise<number> {
  // 生成唯一通知ID(基于时间戳和随机数)
  const notificationId: number = Math.floor(Date.now() % 100000);

  // 构建通知请求对象
  let notificationRequest: notificationManager.NotificationRequest = {
    id: notificationId,
    label: "职位通知",
    content: {
      // 指定为普通文本类型
      notificationContentType: notificationManager.ContentType.NOTIFICATION_CONTENT_BASIC_TEXT,
      normal: {
        title: title,
        text: content,
        // additionalText可选,用于显示摘要信息
        additionalText: "查看详情"
      }
    },
    // 指定通知渠道
    notificationSlotType: slotType
  };

  try {
    // 调用publish API发布通知
    await notificationManager.publish(notificationRequest);
    hilog.info(DOMAIN_NUMBER, TAG, `发布通知成功,ID: ${notificationId}`);
    return notificationId;
  } catch (err) {
    let error = err as BusinessError;
    hilog.error(DOMAIN_NUMBER, TAG,
      `发布通知失败: ${error.code}, ${error.message}`);
    return -1;
  }
}

4.3 支持的其他通知类型

除了普通文本通知,Notification Kit还支持以下通知类型:

通知类型 ContentType常量 使用场景
长文本通知 NOTIFICATION_CONTENT_LONG_TEXT 招聘详情、协议条款、活动规则等需要展开查看的内容
进度条通知 NOTIFICATION_CONTENT_PROGRESS 文件下载、视频上传、数据同步等需要显示进度的任务
多行文本通知 NOTIFICATION_CONTENT_MULTILINE 聊天记录、面试安排、引用内容等需要多行展示的信息

这些通知类型在实现时,只需将NotificationRequest.content.notificationContentType和对应的content对象替换即可。

4.4 通知更新实现

更新通知的核心原理是:使用相同的通知ID和标签(label)发布新通知,系统会用新通知替换旧通知。

旧通知 (ID=1001) + 新通知 (ID=1001) = 新通知替换旧通知

完整实现代码

/**
 * 通知管理器类
 * 管理通知的发布、更新、取消等操作
 */
export class NotificationManager {
  // 通知ID计数器
  private static notificationIdCounter: number = 1000;

  // 存储已发布的通知ID,用于更新和取消
  private static publishedNotifications: Map<string, number> = new Map();

  /**
   * 发布或更新通知
   * @param key 通知的唯一标识key(用于跟踪同一业务的不同通知)
   * @param title 通知标题
   * @param content 通知内容
   * @param slotType 通知渠道类型
   * @returns Promise<number> 通知ID
   *
   * 实现原理:
   * 1. 根据key检查是否已存在相同通知
   * 2. 如果存在,使用相同的ID发布新通知(实现更新)
   * 3. 如果不存在,创建新ID并发布(实现新增)
   */
  static async publishOrUpdateNotification(
    key: string,
    title: string,
    content: string,
    slotType: notificationManager.SlotType = notificationManager.SlotType.SERVICE_INFORMATION
  ): Promise<number> {
    // 生成或获取通知ID
    let notificationId: number;

    if (this.publishedNotifications.has(key)) {
      // 已存在相同通知,使用已有ID(实现更新)
      notificationId = this.publishedNotifications.get(key)!;
      hilog.info(DOMAIN_NUMBER, TAG, `更新通知,ID: ${notificationId}`);
    } else {
      // 不存在,生成新ID(实现新增)
      notificationId = ++this.notificationIdCounter;
      this.publishedNotifications.set(key, notificationId);
      hilog.info(DOMAIN_NUMBER, TAG, `新增通知,ID: ${notificationId}`);
    }

    // 构建通知请求
    const request: notificationManager.NotificationRequest = {
      id: notificationId,
      content: {
        notificationContentType: notificationManager.ContentType.NOTIFICATION_CONTENT_BASIC_TEXT,
        normal: {
          title: title,
          text: content
        }
      },
      notificationSlotType: slotType
    };

    try {
      // 发布通知(新增或更新取决于ID是否已存在)
      await notificationManager.publish(request);
      return notificationId;
    } catch (err) {
      let error = err as BusinessError;
      hilog.error(DOMAIN_NUMBER, TAG, `发布通知失败: ${error.code}`);
      return -1;
    }
  }

  /**
   * 清除所有已发布的通知记录
   */
  static clearAllNotificationRecords(): void {
    this.publishedNotifications.clear();
    hilog.info(DOMAIN_NUMBER, TAG, `已清除所有通知记录`);
  }
}

4.5 取消单个通知

API说明cancel(id: number) 根据通知ID取消已发布的通知。

/**
 * 取消指定通知
 * @param notificationId 要取消的通知ID
 * @returns Promise<void>
 *
 * 注意事项:
 * 1. 只有本应用发布的通知才能取消
 * 2. 如果通知已过期或被用户手动清除,调用cancel会失败
 * 3. 错误码1600007表示通知不存在
 */
static async cancelNotification(notificationId: number): Promise<void> {
  try {
    await notificationManager.cancel(notificationId);
    hilog.info(DOMAIN_NUMBER, TAG, `取消通知成功,ID: ${notificationId}`);
  } catch (err) {
    let error = err as BusinessError;

    // 1600007表示通知不存在,可能已被用户清除或已过期
    if (error.code === 1600007) {
      hilog.warn(DOMAIN_NUMBER, TAG, `通知不存在或已过期,ID: ${notificationId}`);
    } else {
      hilog.error(DOMAIN_NUMBER, TAG, `取消通知失败: ${error.code}, ${error.message}`);
    }
  }
}

/**
 * 根据key取消通知
 * @param key 发布通知时使用的key
 */
static async cancelNotificationByKey(key: string): Promise<void> {
  const notificationId: number | undefined =
    NotificationManager.publishedNotifications.get(key);

  if (notificationId !== undefined) {
    await this.cancelNotification(notificationId);
    NotificationManager.publishedNotifications.delete(key);
  } else {
    hilog.warn(DOMAIN_NUMBER, TAG, `未找到对应的通知,key: ${key}`);
  }
}

4.6 取消所有通知

API说明cancelAll() 取消本应用发布的所有通知。

/**
 * 取消所有通知
 * @returns Promise<void>
 *
 * 使用场景:
 * 1. 用户退出登录时,清除所有相关通知
 * 2. 应用设置中提供"清空所有通知"功能
 * 3. 应用更新时清除旧版本的通知
 *
 * 注意事项:
 * 此操作会取消本应用发布的所有通知,包括所有渠道的通知
 */
static async cancelAllNotifications(): Promise<void> {
  try {
    await notificationManager.cancelAll();
    hilog.info(DOMAIN_NUMBER, TAG, `取消所有通知成功`);

    // 同时清除内存中的记录
    NotificationManager.clearAllNotificationRecords();
  } catch (err) {
    let error = err as BusinessError;
    hilog.error(DOMAIN_NUMBER, TAG, `取消所有通知失败: ${error.code}, ${error.message}`);
  }
}

5. 最佳实践

5.1 权限管理最佳实践

✅ 推荐做法:
┌─────────────────────────────────────────────────────────┐
│ 1. 应用启动时检查权限状态                                 │
│ 2. 权限未启用时,引导用户开启                              │
│ 3. 提供设置入口,让用户自主管理                            │
│ 4. 权限被拒绝后,不再频繁弹窗                              │
│ 5. 记录用户选择,避免重复请求                              │
└─────────────────────────────────────────────────────────┘

❌ 避免做法:
┌─────────────────────────────────────────────────────────┐
│ 1. 不询问直接发送通知(会被系统拦截)                       │
│ 2. 用户拒绝后频繁弹窗请求(影响用户体验)                   │
│ 3. 权限请求时机不当(应在用户有明显需求时请求)             │
│ 4. 没有提供关闭通知的选项                                  │
└─────────────────────────────────────────────────────────┘

5.2 通知ID管理策略

/**
 * 通知ID管理最佳实践
 *
 * 方案一:固定ID + 业务前缀(推荐)
 * - 不同业务使用不同的ID范围
 * - 便于分类管理和统计
 */
const NotificationIdRange = {
  JOB: { start: 1000, end: 1999 },      // 职位相关
  APPLICATION: { start: 2000, end: 2999 }, // 申请相关
  MESSAGE: { start: 3000, end: 3999 },   // 消息相关
  SYSTEM: { start: 9000, end: 9999 }     // 系统通知
};

/**
 * 方案二:动态ID + Map映射(支持更新)
 * - 使用Hash生成唯一ID
 * - 保存key到ID的映射关系
 */
class NotificationIdGenerator {
  private static idCounter: number = 10000;
  private static idMap: Map<string, number> = new Map();

  static generateId(key: string): number {
    if (this.idMap.has(key)) {
      return this.idMap.get(key)!;
    }
    const id = ++this.idCounter;
    this.idMap.set(key, id);
    return id;
  }
}

5.3 性能优化建议

/**
 * 通知发送频率控制
 *
 * 系统限制:每分钟最多发送60条通知
 * 超出限制会返回错误码1600009
 */

// 方案一:节流阀控制
class NotificationThrottle {
  private lastSendTime: number = 0;
  private readonly minInterval: number = 1000; // 最小发送间隔(毫秒)

  async sendNotification(title: string, content: string): Promise<boolean> {
    const now = Date.now();
    if (now - this.lastSendTime < this.minInterval) {
      hilog.warn(DOMAIN_NUMBER, TAG, `通知发送过于频繁,已跳过`);
      return false;
    }

    await NotificationUtil.publishOnce(title, content);
    this.lastSendTime = now;
    return true;
  }
}

// 方案二:消息队列批量处理
class NotificationQueue {
  private queue: Array<{ title: string; content: string }> = [];
  private isProcessing: boolean = false;

  add(title: string, content: string): void {
    this.queue.push({ title, content });
    if (!this.isProcessing) {
      this.processQueue();
    }
  }

  private async processQueue(): Promise<void> {
    if (this.queue.length === 0) {
      this.isProcessing = false;
      return;
    }

    this.isProcessing = true;
    const notification = this.queue.shift()!;

    await NotificationUtil.publishOnce(notification.title, notification.content);

    // 处理完一条后,延迟再处理下一条(符合系统限流)
    await new Promise(resolve => setTimeout(resolve, 1000));
    this.processQueue();
  }
}

6. 注意事项

6.1 权限管理注意事项

  • 不要频繁请求授权:如果用户拒绝了,不要每次启动应用都弹窗请求,这样会让人很烦。可以提供一个设置入口,让用户主动开启。
  • 处理拒绝情况:用户拒绝授权时,错误码是1600004,要妥善处理这种情况,给用户友好的提示。
  • 提前检查权限:在发送通知前,先检查权限状态,避免不必要的错误。
  • 记录用户选择:使用本地存储记录用户的选择,避免重复请求。

6.2 通知ID管理注意事项

  • 避免ID冲突:每个通知都应该有唯一的ID,否则新通知会覆盖旧通知。可以使用哈希算法根据业务数据生成唯一ID。
  • ID范围规划:为不同类型的通知预留不同的ID范围,方便管理和取消。
  • 保存通知ID:如果需要后续更新或取消通知,需要保存通知ID,建议使用Map数据结构管理。

6.3 通知内容注意事项

  • 标题要简洁:通知标题要简短明了,一眼就能看出是什么内容。
  • 内容要具体:通知内容要包含关键信息,让用户不用打开应用就能了解情况。
  • 避免刷屏:不要在短时间内发送大量通知,这样会被用户当成骚扰。
  • 图标要清晰:通知图标要清晰可辨,使用应用图标或自定义通知图标。

6.4 定时任务注意事项

  • 频率要适中:定时检查任务的频率不要太高,1分钟一次是比较合理的选择。
  • 及时清理:页面销毁时,一定要记得停止定时任务,避免内存泄漏。
  • 异常处理:定时任务中要加上异常处理,避免某个通知发送失败影响后续任务。

6.5 用户体验注意事项

  • 提供开关:给用户提供关闭通知的选项,尊重用户的选择。
  • 状态提示:在UI中明确显示通知功能的开启状态,让用户心里有数。
  • 引导设置:如果通知功能被关闭,提供便捷的入口让用户重新开启。
  • 尊重隐私:不要在通知中展示敏感信息,除非用户明确同意。

参考资源


Logo

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

更多推荐