Forum Xamarin Xamarin.Android

Changing the sound for notification channel dynamically

yurylankovskiyyurylankovskiy Member ✭✭
edited January 28 in Xamarin.Android


I require to change the sound for notification channel dynamically. Just a bit of background information, I have three sound files for notification sound placed under Android project in ../Resources/raw/ folder. In Xamarin.Forms project I have a page where a user can select a sound from the list of three files to play for notifications. Prior to generating a notification I check if the sound file selection was changed by the user, and if it has the channel is modified to set the currently selected sound file from resources.

For some reason, the sound does not change until I reboot my application. I have tried destroying the notification channel and re-creating with a new sound as well as just changing the sound for an existing channel. Nothing seems to work, only the application reboot helps.

Now to the code part, I will include only the creation of my channel and say that it is indeed called when the sound is changed, before a notification is generated.

private void CreateNotificationChannel()
    NotificationManager notificationManager = (NotificationManager)this.GetSystemService(Context.NotificationService);

    //Notification Channel
    var isNewChannel = false;
    NotificationChannel notificationChannel = null;

    // fetch existing channel, if one exists, make modifications to sound, otherwise create a new channel
    if ((notificationChannel = notificationManager.GetNotificationChannel(NOTIFICATION_CHANNEL_ID)) == null)
        notificationChannel = new NotificationChannel(NOTIFICATION_CHANNEL_ID, NOTIFICATION_CHANNEL_NAME, NotificationImportance.Max);
        notificationChannel.LightColor = Color.Red;
        notificationChannel.SetVibrationPattern(new long[] { 100, 200, 300, 400, 500, 400, 300, 200, 400 });

        isNewChannel = true;

    if (!string.IsNullOrEmpty(ALARM_NOTIFICATION_SOUND)) {

        var audioResource = 0;
            case "classic":
                audioResource = Resource.Raw.classic;
            case "alarm":
                audioResource = Resource.Raw.alarm;
            case "siren":
                audioResource = Resource.Raw.siren;
        // Creating an Audio Attribute
        var alarmAttributes = new AudioAttributes.Builder()

        // Create the uri for the alarm file                 
        Android.Net.Uri alarmUri = Android.Net.Uri.Parse($"{ContentResolver.SchemeAndroidResource}://{PackageName}/{audioResource}");

        notificationChannel.SetSound(alarmUri, alarmAttributes);

    if (isNewChannel)

    isNotificationChannelCreated = true;

Best Answer


Sign In or Register to comment.