Skip to content

[Android = 26] Notification Channel

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

Setting up Notification Channels

.Net MAUI

public static class MauiProgram
{
	public static MauiApp CreateMauiApp()
	{
		var builder = MauiApp.CreateBuilder();
		builder
			.UseMauiApp<App>()
			.....			
			.UseLocalNotification(config =>
			{                
                                config.AddAndroid(android =>
				{
					android.AddChannel(new NotificationChannelRequest
					{
						Id = $"my_channel_01",
                                                Name = "General",
                                                Description = "General",
					});
                                        android.AddChannel(new NotificationChannelRequest
					{
						Id = $"my_channel_02",
                                                Name = "Special",
                                                Description = "Special",
					});
				});
			});
        
                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 created multiple Notification Channels with different names.
                LocalNotificationCenter.CreateNotificationChannel(
                        new Plugin.LocalNotification.Platform.Droid.NotificationChannelRequest
                        {
                                Id = $"my_channel_01",
                                Name = "General",
                                Description = "General",
                        });

                LocalNotificationCenter.CreateNotificationChannel(
                        new Plugin.LocalNotification.Platform.Droid.NotificationChannelRequest
                        {
                                Id = $"my_channel_02",
                                Name = "Special",
                                Description = "Special",
                        });
		.....	
                LoadApplication(new App());
		.....	
		LocalNotificationCenter.NotifyNotificationTapped(Intent);
	}

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

How to set the Channel Id when sending a notification.

var notification = new NotificationRequest
{
    NotificationId = 100,
    Title = "Test",
    Description = "Test Description"    
};
notification.Android.ChannelId = "my_channel_01";
LocalNotificationCenter.Current.Show(notification);