【发布时间】:2020-04-08 16:24:13
【问题描述】:
当我的 Xamarin 手机应用收到新事件时,会弹出本地通知。这工作正常,它也播放声音。但是,我想根据我的应用收到的事件类型播放不同的声音。我认为这很简单,但是在我重新构建应用程序后首先播放的任何声音都是随后为每个通知播放的声音,无论代码如何。
例如,在重建之后,如果 Priority 枚举是 Priority.Temp 则 TempNotif.wav 将播放。但是,如果代码再次调用此方法以显示另一个通知并且优先级枚举不是 Priority.Temp,则 TempNotif.wav 仍然会播放,即使我已将其设置为播放 StandardNotif.wav。似乎android会复制第一个声音,并且一旦有声音就不会更新它。不管发生什么,我肯定可以针对不同的通知播放不同的声音吗?
代码如下:
public void CreateNotification(string title, string message, Priority priority)
{
Android.Net.Uri sound = null;
if (priority == Priority.Temperature)
{
sound = global::Android.Net.Uri.Parse($!{ContentResolver.SchemeAndroidResource}://{context.PackageName}/{Resource.Raw.TempNotif}");
}
else
{
sound = global::Android.Net.Uri.Parse($!{ContentResolver.SchemeAndroidResource}://{context.PackageName}/{Resource.Raw.StandardNotif}");
}
var alarmAttributes = new AudioAttributes.Builder()
.SetContentType(AudioContentType.Sonification)
.SetUsage(AudioUsageKind.Notification).Build();
builder = new NotificationCompat.Builder(context, notificationChannelId);
builder.SetContentTitle(title)
.SetAutoCancel(true)
.SetContentText(message)
.SetPriority((int)NotificationPriority.High)
.SetSmallIcon(Resource.Drawable.MetroIcon)
.SetColor(00255)
.SetVibrate(new long[0])
.SetSound(sound)
.SetVisibility((int)NotificationVisibility.Public);
notificationManager = context.GetSystemService(Context.NotificationService) as
NotificationManager;
if (global::Android.OS.Build.VERSION.SdkInt >= BuildVersionCodes.O)
{
NotificationImportance importance = NotificationImportance.High;
NotificationChannel notificationChannel = new NotificationChannel(notificationChannelId,
title, importance);
notificationChannel.Importance = NotificationImportance.High;
notificationChannel.EnableLights(true);
notificationChannel.EnableVibration(true);
notificationChannel.SetSound(sound, alarmAttributes);
notificationChannel.SetShowBadge(true);
notificationChannel.SetVibrationPattern(new long[] { 100, 200, 300, 400, 500, 400, 300, 200, 400 });
if (notificationManager != null)
{
builder.SetChannelId(notificationChannelId);
notificationManager.CreateNotificationChannel(notificationChannel);
}
}
notificationManager.Notify(0, builder.Build());
}
【问题讨论】:
-
您需要覆盖您的通知吗?如果在调用 notificationManager.Notify(0, builder.Build()); 时不尝试传递唯一 id 而不是始终传递 0;
-
我回到电脑前会检查这个,谢谢兄弟
-
@DavidAndrewThorpe Notification.Builder setSound 方法在 API 级别 26 中已弃用。改用 NotificationChannel#setSound(Uri, AudioAttributes)。请看:developer.android.com/reference/android/app/…
-
@CherryBu-MSFT 我正在使用 NotificationCompat.Builder,我认为它没有贬值?
-
@CherryBu-MSFT 如果您查看我的代码的下半部分,您会发现我已经在使用 NotificationChannel.SetSound()
标签: android visual-studio xamarin notifications