You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

.NET MAUI中如何使用NotificationChannel.SetSound设置通知渠道声音

在.NET MAUI中为NotificationChannel设置自定义提示音的实现方案

可以实现,.NET MAUI的Android平台层完全支持使用原生Android API创建带自定义提示音的NotificationChannel,无需纠结Android.Net.Uri与System.Uri的兼容问题——因为这部分逻辑仅在Android平台执行,直接使用Android原生类型即可。

具体步骤:

  1. 放置音频资源
    将自定义提示音文件(如alarm.mp3)放入MAUI项目的Platforms/Android/Raw目录(若Raw文件夹不存在则手动创建),注意文件名需为小写,且不含空格或特殊字符。

  2. 编写Android平台特定代码
    由于通知渠道是Android专属功能,需在Platforms/Android目录下的类(如MainActivity.cs或专门的通知管理类)中实现创建逻辑,示例代码如下:

using Android.App;
using Android.Content;
using Android.Media;
using AndroidX.Core.App;

// ... 其他代码

// 创建音频属性配置
var alarmAttributes = new AudioAttributes.Builder()
    .SetContentType(AudioContentType.Sonification)
    .SetUsage(AudioUsageKind.Alarm)
    .Build();

// 构建指向Raw资源的Android原生Uri
var alarmUri = Android.Net.Uri.Parse(
    $"{ContentResolver.SchemeAndroidResource}://{Android.App.Application.Context.PackageName}/raw/alarm");

// 创建并配置通知渠道
var alarmChannel = new NotificationChannel(
    id: Constants.AlarmNotificationChannel,
    name: "Alarm",
    importance: NotificationImportance.Max)
{
    Description = "Highest priority notifications appear in this channel"
};

alarmChannel.EnableLights(true);
alarmChannel.EnableVibration(true);
alarmChannel.SetBypassDnd(true);
alarmChannel.SetShowBadge(true);
alarmChannel.SetSound(alarmUri, alarmAttributes);

// 注册通知渠道到系统
var notificationManager = NotificationManager.FromContext(Android.App.Application.Context);
notificationManager.CreateNotificationChannel(alarmChannel);

关键说明:

  • 直接使用Android.Net.Uri即可,无需转换为System.Uri,这部分代码仅在Android平台运行,完全兼容原生API。
  • 确保Constants.AlarmNotificationChannel是全局唯一的渠道ID,符合Android的命名规范。
  • 若需跨平台触发该逻辑,可通过MAUI的**依赖服务(DependencyService)**封装接口,在Android平台实现中编写上述代码,其他平台留空或做适配处理。

内容的提问来源于stack exchange,提问作者jezzuz

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.02 15:45:35