HarmonyOS 鸿蒙Next中Notification Kit(用户通知服务)如何使用sound自定义提示音

HarmonyOS 鸿蒙Next中Notification Kit(用户通知服务)如何使用sound自定义提示音 【问题描述】:我按照官网文档尝试了,但是一直都是默认的提示音,这个sound该怎么用啊,能给我一个可行的demo吗?这个代码是官网的示例,我修改了一下

【问题现象】:设置了sound也是默认的提示音,这个sound提示是一个string

【版本信息】:6.0.0(20)

【复现代码】:

import { notificationManager } from '@kit.NotificationKit';
import { BusinessError } from '@kit.BasicServicesKit';
import { common } from '@kit.AbilityKit';
import { PromptAction } from '@kit.ArkUI';

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

@Entry
@Component
struct NotificationPage {
  uiContext: UIContext = this.getUIContext();
  promptAction: PromptAction = this.uiContext.getPromptAction();

  // 获取用户授权
  requestForNotification() {
    let context = this.getUIContext().getHostContext() as common.UIAbilityContext;
    notificationManager.isNotificationEnabled().then((data: boolean) => {
      console.info(`${DOMAIN_NUMBER}, ${TAG}, isNotificationEnabled success, data: ${data}`);
      if (!data) {
        notificationManager.requestEnableNotification(context).then(() => {
          this.promptAction.openToast({
            message: '请求通知授权成功',
            duration: 2000,
          });
          console.info(`${DOMAIN_NUMBER}, ${TAG}, [ANS] requestEnableNotification success`);
        }).catch((err: BusinessError) => {
          if (1600004 == err.code) {
            this.promptAction.openToast({
              message: '请求通知授权失败',
              duration: 2000,
            });
            console.error(`${DOMAIN_NUMBER}, ${TAG},
              [ANS] requestEnableNotification refused, code is ${err.code}, message is ${err.message}`);
          } else {
            console.error(`${DOMAIN_NUMBER}, ${TAG},
              [ANS] requestEnableNotification failed, code is ${err.code}, message is ${err.message}`);
          }
        });
      }
    }).catch((err: BusinessError) => {
      console.error(`${DOMAIN_NUMBER}, ${TAG}, isNotificationEnabled fail, code is ${err.code}, message is ${err.message}`);
    });
  }

  // 构造NotificationRequest对象,发布通知
  notification(title: string, message: string) {
    let notificationRequest: notificationManager.NotificationRequest = {
      id: 1,
      content: {
        notificationContentType: notificationManager.ContentType.NOTIFICATION_CONTENT_BASIC_TEXT,
        normal: {
          title: "test_title",
          text: "test_text",
          additionalText: "test_additionalText"
        }
      },
      notificationSlotType: notificationManager.SlotType.SOCIAL_COMMUNICATION,
      sound: 'sound.mp3'
    };
    notificationManager.publish(notificationRequest, (err: BusinessError) => {
      if (err) {
        console.error(`${DOMAIN_NUMBER}, ${TAG}, Failed to publish notification. Code is ${err.code}, message is ${err.message}`);
        this.promptAction.openToast({
          message: '请求通知授权成功',
          duration: 2000,
        });
        return;
      } else {
        console.info(`${DOMAIN_NUMBER}, ${TAG}, Succeeded in publishing notification.`);
        this.promptAction.openToast({
          message: '发布通知成功',
          duration: 2000,
        });
      }
    });
  }

  // 获取二次授权
  openNotification(){
    let context = this.getUIContext().getHostContext() as common.UIAbilityContext;
    notificationManager.isNotificationEnabled().then((data: boolean) => {
      console.info(`${DOMAIN_NUMBER}, ${TAG}, "isNotificationEnabled success, data:${data} `);
      if(!data){
        notificationManager.openNotificationSettings(context).then(() => {
          console.info(`${DOMAIN_NUMBER}, ${TAG}, [ANS] openNotificationSettings success`);
        }).catch((err: BusinessError) => {
          console.error(`${DOMAIN_NUMBER}, ${TAG}, [ANS] openNotificationSettings failed, code is ${err.code}, message is ${err.message}`);
        });
      }
    }).catch((err: BusinessError) => {
      console.error(`${DOMAIN_NUMBER}, ${TAG}, isNotificationEnabled fail, code is ${err.code}, message is ${err.message}`);
    });
  }

  aboutToAppear(): void {
    this.requestForNotification();
    this.openNotification();
  }

  build() {
    Column() {
      Button('发布通知').onClick(() => {
        let title = '这是一个标题';
        let message = '这是一条通知';
        this.notification(title, message);
      });
    }
    .width('100%')
    .height('100%')
    .justifyContent(FlexAlign.Center);
  }
}

更多关于HarmonyOS 鸿蒙Next中Notification Kit(用户通知服务)如何使用sound自定义提示音的实战教程也可以访问 https://www.itying.com/category-93-b0.html

5 回复

开发者你好,参考以下:

【解决方案】 目前自定义通知铃声仅对AppGallery Connect中应用分类为“社交”且应用标签为“通讯”的应用开放。可通过AlertPayload中的sound属性自定义消息通知铃声,使用该属性需要申请自定义铃声权益

【常见FAQ】 Q:如何设置自定义铃声的时长? A:可通过AlertPayload中的soundDuration属性来自定义消息通知铃声时长。

Q:应用通知自定义铃声文件有什么要求? A:该文件必须放在应用的/resources/rawfile路径下,支持m4a、aac、mp3、ogg、wav、flac、amr等格式。

Q:关于Push Kit(推送服务)自定义铃声权益申请功能下线通知,对那些生效? A:自2025年11月17日起,相关权益申请入口将从AGC平台下线,开发者可以直接使用自定义铃声功能,不再需要申请权限(此权益为HarmonyOS权益,不影响其他平台的业务)。已提交但未审核的申请将自动终止,无需处理。已申请过该权益的业务不受影响,无需修改代码或流程。

【背景知识】 PushKit(推送服务)是华为提供的消息推送平台,建立了从云端到终端的消息推送通道。

更多关于HarmonyOS 鸿蒙Next中Notification Kit(用户通知服务)如何使用sound自定义提示音的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html


也就是说只用Notification Kit(用户通知服务)设置消息通知,是不能自定义铃声的,只能用Push Kit(推送服务)的sound来自定义? NotificationRequest官网链接中的sound那是写着干嘛的:https://developer.huawei.com/consumer/cn/doc/harmonyos-references/js-apis-inner-notification-notificationrequest

在HarmonyOS Next中,使用Notification Kit自定义提示音需通过NotificationRequest配置。具体步骤为:在NotificationRequest中设置sound属性,其值为ResourceManager获取的RawFileDescriptor。需先将音频文件置于resources/rawfile目录,然后通过rawFileEntry.openRawFileDescriptor()获取描述符。最后使用NotificationHelper的publishNotification方法发布通知。

在HarmonyOS Next中,自定义通知提示音需要正确配置sound字段,并确保音频文件已正确放置。根据你的代码,问题可能出在音频文件路径或格式上。

以下是关键点:

  1. sound字段的正确使用

    • sound字段应设置为资源引用路径,格式为$rawfile('filename')
    • 示例:sound: $rawfile('sound.mp3')
  2. 修改后的代码片段

let notificationRequest: notificationManager.NotificationRequest = {
  id: 1,
  content: {
    notificationContentType: notificationManager.ContentType.NOTIFICATION_CONTENT_BASIC_TEXT,
    normal: {
      title: "test_title",
      text: "test_text",
      additionalText: "test_additionalText"
    }
  },
  notificationSlotType: notificationManager.SlotType.SOCIAL_COMMUNICATION,
  sound: $rawfile('sound.mp3')  // 修改这里
};
  1. 音频文件放置

    • sound.mp3文件放在项目的resources/rawfile/目录下
    • 支持格式:MP3、WAV等系统支持的音频格式
  2. 完整流程

    • 确保通知权限已授权
    • 音频文件大小适中(建议小于1MB)
    • 测试时设备音量需开启

如果仍然使用默认提示音,请检查:

  • 音频文件路径是否正确
  • 文件格式是否被支持
  • 通知渠道(SlotType)是否允许自定义声音

按照以上方式修改后,应该能正常播放自定义提示音。

回到顶部