HarmonyOS APP开发之NotificationSlot、渠道重要性级别、渠道配置与管理

举报
Jack20 发表于 2026/06/20 13:47:05 2026/06/20
【摘要】 HarmonyOS APP开发之NotificationSlot、渠道重要性级别、渠道配置与管理核心要点:通知渠道(NotificationSlot)是 HarmonyOS 通知体系的"交通管制员",通过重要性级别和细粒度配置,让不同类型的通知拥有不同的展示策略和打扰程度。 一、背景与动机想象一下这个场景:你正在开会,手机突然响了一声——是一条电商促销推送。而真正重要的工作消息,却因为被促...

HarmonyOS APP开发之NotificationSlot、渠道重要性级别、渠道配置与管理

核心要点:通知渠道(NotificationSlot)是 HarmonyOS 通知体系的"交通管制员",通过重要性级别和细粒度配置,让不同类型的通知拥有不同的展示策略和打扰程度。


一、背景与动机

想象一下这个场景:你正在开会,手机突然响了一声——是一条电商促销推送。而真正重要的工作消息,却因为被促销通知"淹没"在通知栏里,你直到散会才看到。

这就是通知渠道要解决的核心问题:不是所有通知都值得同等对待

在 HarmonyOS 中,通知渠道就像快递的"配送等级"——加急件走航空、普通件走陆运、免打扰件放驿站。通过 NotificationSlot,你可以为不同类型的通知设置不同的重要性级别、声音、振动和展示方式。用户也可以在系统设置中,针对每个渠道单独调整偏好——比如关闭营销推送但保留订单通知。

这个设计思路借鉴了 Android 8.0 引入的 Notification Channel 机制,但在 HarmonyOS 中做了更精细化的适配。理解通知渠道,是做好通知体验的第一步。


二、核心原理

2.1 通知渠道架构

flowchart TD
    A[应用创建 NotificationSlot] --> B[设置渠道类型 SlotType]
    B --> C[配置渠道参数]
    C --> D[调用 addSlot 注册渠道]
    D --> E[渠道注册到系统]
    
    F[应用发布通知] --> G[指定 slotType]
    G --> H{系统查找对应渠道}
    H -->|找到| I[按渠道配置展示通知]
    H -->|未找到| J[使用默认渠道配置]
    
    I --> K[用户可在设置中调整渠道]
    K --> L[渠道配置动态生效]
    
    classDef primary fill:#4CAF50,stroke:#388E3C,color:#fff
    classDef warning fill:#FF9800,stroke:#F57C00,color:#fff
    classDef error fill:#F44336,stroke:#D32F2F,color:#fff
    classDef info fill:#2196F3,stroke:#1976D2,color:#fff
    classDef purple fill:#9C27B0,stroke:#7B1FA2,color:#fff
    
    class A,B,C,D primary
    class E,I,K,L info
    class F,G warning
    class J error

2.2 SlotType 渠道类型

HarmonyOS 预定义了以下渠道类型,每种类型对应不同的使用场景:

SlotType 适用场景 默认重要性
SOCIAL_COMMUNICATION 0 社交通信(消息、聊天) HIGH
SERVICE_INFORMATION 1 服务提醒(订单、物流) DEFAULT
CONTENT_INFORMATION 2 内容推荐(新闻、资讯) LOW
OTHER_TYPES 3 其他类型(营销、广告) MIN
CUSTOM 4 自定义渠道 开发者指定

2.3 重要性级别详解

重要性级别决定了通知的打扰程度和展示方式,这是通知渠道最核心的配置项:

级别 展示方式 声音 振动 锁屏
LEVEL_NONE 0 不展示
LEVEL_MIN 1 状态栏小图标
LEVEL_LOW 2 状态栏+通知栏
LEVEL_DEFAULT 3 状态栏+通知栏+横幅
LEVEL_HIGH 4 全部展示+锁屏
flowchart LR
    A[LEVEL_NONE<br/>不展示] --> B[LEVEL_MIN<br/>仅图标]
    B --> C[LEVEL_LOW<br/>通知栏]
    C --> D[LEVEL_DEFAULT<br/>横幅+声音]
    D --> E[LEVEL_HIGH<br/>锁屏+振动]
    
    A -.- F[打扰程度:]
    B -.- G[打扰程度: 极低]
    C -.- H[打扰程度:]
    D -.- I[打扰程度:]
    E -.- J[打扰程度:]
    
    classDef primary fill:#4CAF50,stroke:#388E3C,color:#fff
    classDef warning fill:#FF9800,stroke:#F57C00,color:#fff
    classDef error fill:#F44336,stroke:#D32F2F,color:#fff
    classDef info fill:#2196F3,stroke:#1976D2,color:#fff
    classDef purple fill:#9C27B0,stroke:#7B1FA2,color:#fff
    
    class A primary
    class B info
    class C warning
    class D warning
    class E error
    class F,G,H,I,J purple

2.4 NotificationSlot 完整字段

interface NotificationSlot {
  type: SlotType;                    // 渠道类型(必填)
  level?: SlotLevel;                 // 重要性级别
  desc?: string;                     // 渠道描述(展示给用户)
  badgeFlag?: boolean;               // 是否显示角标
  bypassDnd?: boolean;               // 是否绕过免打扰模式
  lockscreenVisibility?: LockscreenVisibility;  // 锁屏可见性
  sound?: string;                    // 通知声音URI
  vibrationValues?: Array<number>;   // 振动模式
  lightEnabled?: boolean;            // 是否启用呼吸灯
  lightColor?: number;               // 呼吸灯颜色
  enabled?: boolean;                 // 渠道是否启用
}

2.5 渠道与通知的关系

一条通知必须关联一个渠道。如果发布通知时指定的渠道不存在,系统会使用默认渠道。这种机制确保了每条通知都有明确的"归属"。


三、代码实战

3.1 创建与注册通知渠道

这是使用通知渠道的第一步——就像先修路,再通车。

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

@Entry
@Component
struct NotificationSlotCreatePage {
  @State slotStatus: string = '等待创建渠道...';

  /**
   * 创建社交通信渠道
   * 用于即时消息、聊天等高优先级场景
   */
  async createSocialSlot(): Promise<void> {
    const socialSlot: notificationManager.NotificationSlot = {
      type: notificationManager.SlotType.SOCIAL_COMMUNICATION,
      level: notificationManager.SlotLevel.LEVEL_HIGH,  // 高优先级:锁屏+振动+声音
      desc: '即时消息通知,包括聊天消息和好友动态',  // 描述会展示给用户
      badgeFlag: true,        // 显示角标
      bypassDnd: false,       // 不绕过免打扰
      lockscreenVisibility: notificationManager.LockscreenVisibility.LOCKSCREEN_VISIBILITY_PUBLIC,  // 锁屏公开展示
      enabled: true           // 渠道启用
    };

    try {
      await notificationManager.addSlot(socialSlot);
      this.slotStatus = '社交通信渠道创建成功 ✅\n级别: HIGH | 角标: 开 | 锁屏: 公开';
      console.info('[渠道] 社交通信渠道创建成功');
    } catch (err) {
      const error = err as BusinessError;
      this.slotStatus = `创建失败: ${error.message}`;
      console.error(`[渠道] 创建失败: ${error.code}`);
    }
  }

  /**
   * 创建服务信息渠道
   * 用于订单状态、物流更新等中等优先级场景
   */
  async createServiceSlot(): Promise<void> {
    const serviceSlot: notificationManager.NotificationSlot = {
      type: notificationManager.SlotType.SERVICE_INFORMATION,
      level: notificationManager.SlotLevel.LEVEL_DEFAULT,  // 中优先级:横幅+声音
      desc: '服务提醒通知,包括订单状态和物流更新',
      badgeFlag: true,
      bypassDnd: false,
      lockscreenVisibility: notificationManager.LockscreenVisibility.LOCKSCREEN_VISIBILITY_PRIVATE,  // 锁屏隐藏内容
      enabled: true
    };

    try {
      await notificationManager.addSlot(serviceSlot);
      this.slotStatus = '服务信息渠道创建成功 ✅\n级别: DEFAULT | 角标: 开 | 锁屏: 隐藏内容';
      console.info('[渠道] 服务信息渠道创建成功');
    } catch (err) {
      const error = err as BusinessError;
      this.slotStatus = `创建失败: ${error.message}`;
    }
  }

  /**
   * 创建内容信息渠道
   * 用于新闻推荐、资讯推送等低优先级场景
   */
  async createContentSlot(): Promise<void> {
    const contentSlot: notificationManager.NotificationSlot = {
      type: notificationManager.SlotType.CONTENT_INFORMATION,
      level: notificationManager.SlotLevel.LEVEL_LOW,  // 低优先级:仅通知栏
      desc: '内容推荐通知,包括新闻和资讯推送',
      badgeFlag: false,       // 不显示角标
      bypassDnd: false,
      lockscreenVisibility: notificationManager.LockscreenVisibility.LOCKSCREEN_VISIBILITY_HIDE,  // 锁屏不展示
      enabled: true
    };

    try {
      await notificationManager.addSlot(contentSlot);
      this.slotStatus = '内容信息渠道创建成功 ✅\n级别: LOW | 角标: 关 | 锁屏: 不展示';
      console.info('[渠道] 内容信息渠道创建成功');
    } catch (err) {
      const error = err as BusinessError;
      this.slotStatus = `创建失败: ${error.message}`;
    }
  }

  build() {
    Scroll() {
      Column({ space: 16 }) {
        Text('通知渠道创建')
          .fontSize(24)
          .fontWeight(FontWeight.Bold)

        Text(this.slotStatus)
          .fontSize(14)
          .width('90%')
          .padding(16)
          .borderRadius(12)
          .backgroundColor('#F0F4F8')
          .minHeight(80)

        Button('创建社交通信渠道 (HIGH)')
          .width('80%')
          .height(50)
          .backgroundColor('#F44336')
          .onClick(() => this.createSocialSlot())

        Button('创建服务信息渠道 (DEFAULT)')
          .width('80%')
          .height(50)
          .backgroundColor('#FF9800')
          .onClick(() => this.createServiceSlot())

        Button('创建内容信息渠道 (LOW)')
          .width('80%')
          .height(50)
          .backgroundColor('#4CAF50')
          .onClick(() => this.createContentSlot())
      }
      .width('100%')
      .padding(20)
    }
    .width('100%')
    .height('100%')
  }
}

3.2 渠道查询与管理

创建渠道后,我们需要能够查询和管理它们——就像物业管理员需要知道小区里有哪些设施一样。

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

@Entry
@Component
struct NotificationSlotManagePage {
  @State slotListInfo: string = '暂无渠道信息';
  @State activeSlotCount: number = 0;

  /**
   * 获取所有已创建的通知渠道
   * 返回 NotificationSlot 数组,包含每个渠道的完整配置
   */
  async queryAllSlots(): Promise<void> {
    try {
      const slots: Array<notificationManager.NotificationSlot> = 
        await notificationManager.getSlots();
      
      this.activeSlotCount = slots.length;
      
      if (slots.length === 0) {
        this.slotListInfo = '暂无已创建的渠道';
        return;
      }

      // 格式化展示渠道信息
      const slotDetails = slots.map((slot, index) => {
        const typeNames: Record<number, string> = {
          0: '社交通信',
          1: '服务信息',
          2: '内容信息',
          3: '其他类型',
          4: '自定义'
        };
        const levelNames: Record<number, string> = {
          0: 'NONE(不展示)',
          1: 'MIN(仅图标)',
          2: 'LOW(通知栏)',
          3: 'DEFAULT(横幅+声音)',
          4: 'HIGH(锁屏+振动)'
        };
        return `📌 渠道${index + 1}:\n` +
          `  类型: ${typeNames[slot.type] || '未知'}\n` +
          `  级别: ${levelNames[slot.level] || '未知'}\n` +
          `  描述: ${slot.desc || '无'}\n` +
          `  角标: ${slot.badgeFlag ? '开' : '关'}\n` +
          `  启用: ${slot.enabled ? '是' : '否'}`;
      }).join('\n\n');

      this.slotListInfo = `${slots.length} 个渠道:\n\n${slotDetails}`;
      console.info(`[渠道] 查询到 ${slots.length} 个渠道`);
    } catch (err) {
      const error = err as BusinessError;
      this.slotListInfo = `查询失败: ${error.message}`;
      console.error(`[渠道] 查询失败: ${error.code}`);
    }
  }

  /**
   * 获取指定类型的通知渠道
   * 精确查询某个渠道的配置
   */
  async querySlotByType(slotType: notificationManager.SlotType): Promise<void> {
    try {
      const slot = await notificationManager.getSlot(slotType);
      if (slot) {
        this.slotListInfo = `查询到渠道:\n` +
          `  类型: ${slot.type}\n` +
          `  级别: ${slot.level}\n` +
          `  描述: ${slot.desc || '无'}\n` +
          `  角标: ${slot.badgeFlag ? '开' : '关'}`;
        console.info(`[渠道] 查询到类型 ${slotType} 的渠道`);
      } else {
        this.slotListInfo = `未找到类型 ${slotType} 的渠道`;
        console.warn(`[渠道] 类型 ${slotType} 的渠道不存在`);
      }
    } catch (err) {
      const error = err as BusinessError;
      this.slotListInfo = `查询失败: ${error.message}`;
    }
  }

  /**
   * 删除指定类型的通知渠道
   * 删除后,该渠道关联的通知将使用默认渠道
   */
  async removeSlot(slotType: notificationManager.SlotType): Promise<void> {
    try {
      await notificationManager.removeSlot(slotType);
      this.slotListInfo = `渠道类型 ${slotType} 已删除`;
      console.info(`[渠道] 删除渠道类型 ${slotType} 成功`);
      // 刷新渠道列表
      await this.queryAllSlots();
    } catch (err) {
      const error = err as BusinessError;
      this.slotListInfo = `删除失败: ${error.message}`;
      console.error(`[渠道] 删除失败: ${error.code}`);
    }
  }

  /**
   * 删除所有通知渠道
   * 谨慎操作!删除后所有通知将使用默认渠道
   */
  async removeAllSlots(): Promise<void> {
    try {
      await notificationManager.removeAllSlots();
      this.slotListInfo = '所有渠道已删除';
      this.activeSlotCount = 0;
      console.info('[渠道] 所有渠道已删除');
    } catch (err) {
      const error = err as BusinessError;
      this.slotListInfo = `删除失败: ${error.message}`;
    }
  }

  build() {
    Scroll() {
      Column({ space: 16 }) {
        Text('通知渠道管理')
          .fontSize(24)
          .fontWeight(FontWeight.Bold)

        Text(`当前渠道数: ${this.activeSlotCount}`)
          .fontSize(16)
          .fontColor('#666666')

        // 渠道信息展示区
        Scroll() {
          Text(this.slotListInfo)
            .fontSize(13)
            .width('100%')
            .padding(16)
        }
        .width('90%')
        .height(200)
        .borderRadius(12)
        .backgroundColor('#F0F4F8')

        Button('查询所有渠道')
          .width('80%')
          .height(45)
          .backgroundColor('#2196F3')
          .onClick(() => this.queryAllSlots())

        Button('查询社交通信渠道')
          .width('80%')
          .height(45)
          .backgroundColor('#4CAF50')
          .onClick(() => this.querySlotByType(notificationManager.SlotType.SOCIAL_COMMUNICATION))

        Button('删除服务信息渠道')
          .width('80%')
          .height(45)
          .backgroundColor('#FF9800')
          .onClick(() => this.removeSlot(notificationManager.SlotType.SERVICE_INFORMATION))

        Button('删除所有渠道')
          .width('80%')
          .height(45)
          .backgroundColor('#F44336')
          .onClick(() => this.removeAllSlots())
      }
      .width('100%')
      .padding(20)
    }
    .width('100%')
    .height('100%')
  }
}

3.3 渠道与通知联动:完整实战

这是最重要的示例——将渠道和通知结合起来,展示不同渠道下通知的实际表现差异。

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

@Entry
@Component
struct SlotNotificationIntegrationPage {
  @State logText: string = '请先初始化渠道,再发布通知';

  /**
   * 初始化所有通知渠道
   * 应用启动时调用,确保渠道已注册
   */
  async initAllSlots(): Promise<void> {
    const slots: Array<notificationManager.NotificationSlot> = [
      {
        // 社交通信:高优先级,锁屏展示
        type: notificationManager.SlotType.SOCIAL_COMMUNICATION,
        level: notificationManager.SlotLevel.LEVEL_HIGH,
        desc: '好友消息和聊天通知',
        badgeFlag: true,
        bypassDnd: false,
        lockscreenVisibility: notificationManager.LockscreenVisibility.LOCKSCREEN_VISIBILITY_PUBLIC,
        enabled: true
      },
      {
        // 服务信息:中优先级,锁屏隐藏内容
        type: notificationManager.SlotType.SERVICE_INFORMATION,
        level: notificationManager.SlotLevel.LEVEL_DEFAULT,
        desc: '订单和物流通知',
        badgeFlag: true,
        bypassDnd: false,
        lockscreenVisibility: notificationManager.LockscreenVisibility.LOCKSCREEN_VISIBILITY_PRIVATE,
        enabled: true
      },
      {
        // 内容信息:低优先级,锁屏不展示
        type: notificationManager.SlotType.CONTENT_INFORMATION,
        level: notificationManager.SlotLevel.LEVEL_LOW,
        desc: '新闻和资讯推送',
        badgeFlag: false,
        bypassDnd: false,
        lockscreenVisibility: notificationManager.LockscreenVisibility.LOCKSCREEN_VISIBILITY_HIDE,
        enabled: true
      }
    ];

    try {
      // 批量添加渠道
      for (const slot of slots) {
        await notificationManager.addSlot(slot);
      }
      this.logText = '✅ 3个渠道初始化完成\n' +
        '• 社交通信: HIGH 级别\n' +
        '• 服务信息: DEFAULT 级别\n' +
        '• 内容信息: LOW 级别';
      console.info('[渠道] 所有渠道初始化成功');
    } catch (err) {
      const error = err as BusinessError;
      this.logText = `初始化失败: ${error.message}`;
    }
  }

  /**
   * 通过社交通信渠道发布通知
   * 高优先级:锁屏展示 + 声音 + 振动
   */
  async publishSocialNotification(): Promise<void> {
    const request: notificationManager.NotificationRequest = {
      id: 1001,
      slotType: notificationManager.SlotType.SOCIAL_COMMUNICATION,  // 指定渠道
      content: {
        contentType: notificationManager.ContentType.NOTIFICATION_CONTENT_BASIC_TEXT,
        normal: {
          title: '好友消息',
          text: '小明: 周末一起打球吗?'
        }
      },
      showDeliveryTime: true
    };

    try {
      await notificationManager.publish(request);
      this.logText = '📤 社交通知已发布\n渠道: SOCIAL_COMMUNICATION\n级别: HIGH(锁屏+声音+振动)';
    } catch (err) {
      const error = err as BusinessError;
      this.logText = `发布失败: ${error.message}`;
    }
  }

  /**
   * 通过服务信息渠道发布通知
   * 中优先级:横幅 + 声音
   */
  async publishServiceNotification(): Promise<void> {
    const request: notificationManager.NotificationRequest = {
      id: 1002,
      slotType: notificationManager.SlotType.SERVICE_INFORMATION,  // 指定渠道
      content: {
        contentType: notificationManager.ContentType.NOTIFICATION_CONTENT_BASIC_TEXT,
        normal: {
          title: '物流更新',
          text: '您的包裹已到达配送站,预计今日送达'
        }
      },
      showDeliveryTime: true
    };

    try {
      await notificationManager.publish(request);
      this.logText = '📤 服务通知已发布\n渠道: SERVICE_INFORMATION\n级别: DEFAULT(横幅+声音)';
    } catch (err) {
      const error = err as BusinessError;
      this.logText = `发布失败: ${error.message}`;
    }
  }

  /**
   * 通过内容信息渠道发布通知
   * 低优先级:仅通知栏
   */
  async publishContentNotification(): Promise<void> {
    const request: notificationManager.NotificationRequest = {
      id: 1003,
      slotType: notificationManager.SlotType.CONTENT_INFORMATION,  // 指定渠道
      content: {
        contentType: notificationManager.ContentType.NOTIFICATION_CONTENT_BASIC_TEXT,
        normal: {
          title: '今日推荐',
          text: '5个提升效率的开发工具,第3个你一定不知道'
        }
      },
      showDeliveryTime: true
    };

    try {
      await notificationManager.publish(request);
      this.logText = '📤 内容通知已发布\n渠道: CONTENT_INFORMATION\n级别: LOW(仅通知栏)';
    } catch (err) {
      const error = err as BusinessError;
      this.logText = `发布失败: ${error.message}`;
    }
  }

  build() {
    Scroll() {
      Column({ space: 16 }) {
        Text('渠道与通知联动')
          .fontSize(24)
          .fontWeight(FontWeight.Bold)

        Text(this.logText)
          .fontSize(14)
          .width('90%')
          .padding(16)
          .borderRadius(12)
          .backgroundColor('#F0F4F8')
          .minHeight(100)

        Button('① 初始化所有渠道')
          .width('80%')
          .height(50)
          .backgroundColor('#9C27B0')
          .onClick(() => this.initAllSlots())

        Divider().width('80%')

        Text('发布不同渠道的通知:')
          .fontSize(14)
          .fontColor('#666666')

        Button('社交通知 (HIGH)')
          .width('80%')
          .height(45)
          .backgroundColor('#F44336')
          .onClick(() => this.publishSocialNotification())

        Button('服务通知 (DEFAULT)')
          .width('80%')
          .height(45)
          .backgroundColor('#FF9800')
          .onClick(() => this.publishServiceNotification())

        Button('内容通知 (LOW)')
          .width('80%')
          .height(45)
          .backgroundColor('#4CAF50')
          .onClick(() => this.publishContentNotification())

        Button('清除所有通知')
          .width('80%')
          .height(45)
          .backgroundColor('#757575')
          .onClick(async () => {
            await notificationManager.cancelAll();
            this.logText = '所有通知已清除';
          })
      }
      .width('100%')
      .padding(20)
    }
    .width('100%')
    .height('100%')
  }
}

四、踩坑与注意事项

4.1 渠道创建后不可修改级别

这是最重要的坑! 一旦渠道被创建并注册到系统,其重要性级别(level)就不可被应用修改了。这是出于用户体验考虑——防止应用偷偷提高通知的打扰程度。

// ❌ 错误理解:以为重新 addSlot 可以修改级别
// 实际上,如果渠道已存在,addSlot 不会更新 level
await notificationManager.addSlot({
  type: notificationManager.SlotType.SOCIAL_COMMUNICATION,
  level: notificationManager.SlotLevel.LEVEL_HIGH  // 如果渠道已存在,这行不生效
});

// ✅ 正确做法:首次创建时就设置好级别
// 如果确实需要修改,只能引导用户到系统设置中手动调整

解决方案:在应用首次启动时就规划好所有渠道的级别,后续只能引导用户到系统设置中修改。

4.2 渠道描述的重要性

desc 字段不是"可选的装饰"——它会展示在系统设置的通知渠道列表中,帮助用户理解这个渠道的用途。

// ❌ 差的描述
desc: '通知'  // 用户看了也不知道是什么

// ✅ 好的描述
desc: '好友消息和群聊通知,关闭后将无法收到即时消息提醒'

4.3 默认渠道的陷阱

如果发布通知时指定的 slotType 对应的渠道不存在,系统会使用默认渠道。默认渠道的级别通常是 LEVEL_DEFAULT,这可能不是你想要的。

// 如果没有先创建 SOCIAL_COMMUNICATION 渠道就发布通知
const request = {
  id: 1,
  slotType: notificationManager.SlotType.SOCIAL_COMMUNICATION,  // 渠道未注册!
  content: { ... }
};
// 通知会使用默认渠道,级别可能不符合预期

建议:在应用启动时统一初始化所有渠道,确保每条通知都能匹配到正确的渠道。

4.4 addSlot 的幂等性

对同一个 type 多次调用 addSlot() 不会报错,但也不会更新已存在的渠道配置。这意味着你可以安全地在应用启动时重复调用 addSlot(),无需担心重复创建。

4.5 角标(Badge)与渠道的关系

角标的显示受渠道的 badgeFlag 控制。如果渠道设置了 badgeFlag: false,即使通知成功发布,也不会在应用图标上显示角标数字。这对于内容推荐类通知特别有用——你不想让每条新闻推送都增加角标数字。


五、HarmonyOS 6 适配

5.1 API 变更

变更项 HarmonyOS 5 HarmonyOS 6
渠道数量限制 无明确限制 建议不超过10个渠道
渠道分组 不支持 新增 NotificationSlotGroup
动态级别调整 不支持 用户可在设置中调整级别
渠道描述 可选 强制要求填写

5.2 迁移指南

  1. 添加渠道描述:HarmonyOS 6 强制要求渠道必须有 desc 字段,迁移时需补充。

  2. 渠道分组:如果你的应用有多个渠道,建议使用 NotificationSlotGroup 进行分组管理:

// HarmonyOS 6 新增的渠道分组
const slotGroup: notificationManager.NotificationSlotGroup = {
  id: 'message_group',
  name: '消息通知',
  description: '所有消息类通知',
  slots: []  // 关联的渠道列表
};
  1. 精简渠道数量:HarmonyOS 6 建议每个应用不超过10个渠道,过多的渠道会让用户在设置中感到困惑。

六、总结

mindmap
  root((通知渠道))
    核心概念
      NotificationSlot
      SlotType 渠道类型
      SlotLevel 重要性级别
      渠道是通知的"交通规则"
    渠道类型
      SOCIAL_COMMUNICATION 社交通信
      SERVICE_INFORMATION 服务信息
      CONTENT_INFORMATION 内容信息
      OTHER_TYPES 其他类型
    重要性级别
      LEVEL_NONE 不展示
      LEVEL_MIN 仅图标
      LEVEL_LOW 通知栏
      LEVEL_DEFAULT 横幅+声音
      LEVEL_HIGH 锁屏+振动
    渠道管理
      addSlot 创建渠道
      getSlots 查询所有渠道
      getSlot 查询指定渠道
      removeSlot 删除渠道
      removeAllSlots 删除所有渠道
    注意事项
      级别创建后不可修改
      desc 描述必须有意义
      先创建渠道再发通知
      addSlot 具有幂等性
      角标受 badgeFlag 控制
知识点 要点
渠道创建 addSlot() 注册渠道,应用启动时统一初始化
级别选择 根据通知的紧急程度选择合适的 SlotLevel
渠道查询 getSlots() 获取所有渠道,getSlot(type) 获取指定渠道
渠道删除 removeSlot(type) 删除指定渠道,removeAllSlots() 清空
通知绑定 NotificationRequest 中通过 slotType 指定渠道
级别不可变 渠道创建后,重要性级别不可被应用修改
描述必填 desc 字段会展示给用户,必须清晰有意义

通知渠道是做好通知体验的基石。通过合理规划渠道类型和级别,你可以让用户只被打扰"该被打扰"的事。下一篇我们将深入通知样式,看看如何让通知内容更丰富、更吸引人。

【声明】本内容来自华为云开发者社区博主,不代表华为云及华为云开发者社区的观点和立场。转载时必须标注文章的来源(华为云社区)、文章链接、文章作者等基本信息,否则作者和本社区有权追究责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@huaweicloud.com
  • 点赞
  • 收藏
  • 关注作者

评论(0

0/1000
抱歉,系统识别当前为高风险访问,暂不支持该操作

全部回复

上滑加载中

设置昵称

在此一键设置昵称,即可参与社区互动!

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。