Skip to content

Notification with a Sound File

Elvin (Tharindu) Thudugala edited this page Aug 1, 2022 · 18 revisions

Show local notification

.Net MAUI

var notification = new NotificationRequest
{
    NotificationId = 100,
    Title = "Test",
    Description = "Test Description",
    // if not specified, default sound will be played. In Android, this must be set at the channel level. 
    Sound = DeviceInfo.Platform == DevicePlatform.Android ?  "<file name without extension>" : "file name with extension", 
};
LocalNotificationCenter.Current.Show(notification);

Xamarin.Forms

var notification = new NotificationRequest
{
    NotificationId = 100,
    Title = "Test",
    Description = "Test Description",
    // if not specified, default sound will be played. In Android, this must be set at the channel level. 
    Sound = Device.RuntimePlatform == Device.Android ?  "<file name without extension>" : "file name with extension", 
};
LocalNotificationCenter.Current.Show(notification);

Android

.Net MAUI

Add the sound file under Platforms\Android\Resources\raw (create the raw folder if does not exist)

image

Xamarin.Forms

Add the sound file under Resources\raw (create the raw folder if does not exist)

image

When Android >= 26, Sound must be set in Channel level. (After Version 4.0.0).

Create different Notification Channels with different names if you want to play different sound files.

.Net MAUI

public static class MauiProgram { public static MauiApp CreateMauiApp() { var builder = MauiApp.CreateBuilder(); builder .UseMauiApp() .ConfigureFonts(fonts => { fonts.AddFont("OpenSans-Regular.ttf", "OpenSansRegular"); fonts.AddFont("OpenSans-Semibold.ttf", "OpenSansSemibold"); }) //.UseLocalNotification(); .UseLocalNotification(config => { config.AddAndroid(android => { android.AddChannel(new NotificationChannelRequest { Sound = "good_things_happen" }); }); }); return builder.Build(); } }

Xamarin.Forms

public class MainActivity : global::Xamarin.Forms.Platform.Android.FormsAppCompatActivity
{
	protected override void OnCreate(Bundle savedInstanceState)
	{
                .....
                // Must create a Notification Channel when API >= 26
                // you can create multiple Notification Channels with different names.
                LocalNotificationCenter.CreateNotificationChannel(
                        new Plugin.LocalNotification.Platform.Droid.NotificationChannelRequest
                        {
                                Sound = Resource.Raw.<file name without extension>.ToString()
                        });
		.....	
                LoadApplication(new App());
		.....	
		LocalNotificationCenter.NotifyNotificationTapped(Intent);
	}

	protected override void OnNewIntent(Intent intent)
	{
		LocalNotificationCenter.NotifyNotificationTapped(intent);
		base.OnNewIntent(intent);
	}
}

iOS

Add the sound file under Resources.

image

Clone this wiki locally