Xamarin.Android警报管理器SetSound MP3文件

时间:2019-05-03 14:00:24

标签: android xamarin xamarin.forms xamarin.android alarmmanager

我有LocalNotificationService,并且正在那里为Android创建通知。如何将名为Sound_04669的自定义声音添加到AlarmManager而不是RingtoneManager.GetDefaultUri(RingtoneType.Alarm)

我的建筑通知代码:

//Generating notification       
        var builder = new NotificationCompat.Builder(Application.Context)       
            .SetContentTitle(notification.Title)       
            .SetContentText(notification.Body)       
            .SetSmallIcon(notification.IconId)       
            .SetSound(RingtoneManager.GetDefaultUri(RingtoneType.Alarm))       
            .SetAutoCancel(true);       

谢谢大家!

1 个答案:

答案 0 :(得分:0)

您尝试过吗?

var alarmUri = Android.Net.Uri.Parse("MyApp.Android/Resources/raw/alarm.mp3");

这是完整的代码

private void createNotificationChannel()
            {
                var channelName = GetString(Resource.String.noti_chan_urgent);
                var channelDescription = GetString(Resource.String.noti_chan_urgent_description);

                // set the vibration patterm for the channel
                long[] vibrationPattern = { 100, 200, 300, 400, 500, 400, 300, 200, 400 };

                // Creating an Audio Attribute
               var alarmAttributes = new AudioAttributes.Builder()
                                      .SetContentType(AudioContentType.Sonification)
                                      .SetUsage(AudioUsageKind.Alarm)
                                      .Build();

                // Create the uri for the alarm file
                // Note: Make sure you add the mp3 file in your Android project under Resources/raw/soundFile.mp3 and set the build as Android Resource
                var alarmUri = Android.Net.Uri.Parse("MyApp.Android/Resources/raw/alarm.mp3");   


                // create chan1  which is the urgent notifications channel
                var chan1 = new NotificationChannel(PRIMARY_CHANNEL_ID, channelName, NotificationImportance.High)
                {
                    Description = channelDescription
                };


                // set the channel properties
                chan1.EnableLights(true);
                chan1.LightColor = Color.Red;
                chan1.EnableVibration(true);   
                chan1.SetVibrationPattern(vibrationPattern);
                chan1.SetSound(alarmUri, alarmAttributes);          // this is where the sound is set for the channel
                chan1.SetBypassDnd(true);
                chan1.LockscreenVisibility = NotificationVisibility.Public;

                // finally create the channel
                var manager = (NotificationManager)GetSystemService(NotificationService);
                manager.CreateNotificationChannel(chan1);
            }

        }