Spread the love

I managed to fall into the deep end with the list of things I needed to finish off and do. This is the reason I missed a few posts, and had less time to organise my progress in Active e-Fitness. I decided to focus on the highest priority small additions for a while, this way I could fit the work in.

The first problem was organising notifications. It doesn’t help if you wake early and get side tracked when getting up by the tasks you kept yourself busy with. I needed a way to bug myself to do my exercise. It took trial, and error, over more than week, but I found what seems to be the most suitable reliable way in my Android 13 Xamarin C# project.

e-Fitness after 1 day skipped

Notifications in Xamarin C# 11 for Android 13

First off, you can take a look at the test project if you’d like: Xam.Notify (0.9 mb)

Create the abstract class INotify we want to send in from the Android project:

using System;

namespace XamNotify
{
    public abstract class INotify
    {
        public abstract void Notify();
        public abstract void SendNotification(DateTime when, int channel, string title, string description, string callbackMessage);
    }
}

It uses the nuget package Plugin.Localnotification, v10.1.4. Add it to your Android project. First, create the Notifier class instance of INotify for yourself:

namespace XamNotify
{
    public class Notifier : INotify
    {
        public DateTime When { get; set; }
        public int Channel { get; set; }
        public string Title { get; set; }
        public string Description { get; set; }
        public string CallbackMessage { get; set; }
        /// <summary>
        /// Send a notification
        /// </summary>
        /// <param name="when">When to show the notification</param>
        /// <param name="channel">Channel to send it on, e.g. 100, 101, 102, ...</param>
        /// <param name="title">Title of the notification</param>
        /// <param name="description">Description of the notification</param>
        /// <param name="callbackMessage">Message notification sends to app when opened from notification</param>
        public override void SendNotification(DateTime when, int channel, string title, string description, string callbackMessage)
        {
            When = when;
            Channel = channel;
            Title = title;
            Description = description;
            CallbackMessage = callbackMessage;
            Notify();
        }

        public Notifier()
        {
            When = DateTime.Now.AddSeconds(15);
            Channel = 100;
            Title = "Title";
            Description = "Description";
            CallbackMessage = "CallbackMessage";

            LocalNotificationCenter.Current.CancelAll();
            LocalNotificationCenter.Current.ClearAll();
        }

        public override async void Notify()
        {
            if (await LocalNotificationCenter.Current.AreNotificationsEnabled() == false)
            {
                await LocalNotificationCenter.Current.RequestNotificationPermission();
            }

            var notification = new NotificationRequest
            {
                NotificationId = Channel,
                Title = Title,
                Description = Description,
                ReturningData = CallbackMessage,
                Schedule =
                {
                    NotifyTime = When
                }
            }; 
            // This wouldn't work for me, but creation CancelAll and ClearAll seems to work?
            //LocalNotificationCenter.Current.Clear(new int[] { Channel });
            //LocalNotificationCenter.Current.Cancel(new int[] { Channel });
            await LocalNotificationCenter.Current.Show(notification);
        }
    }
}

The two main points to think of when doing this:

  • There needs to be a method for removing the notifications. For instance, if a user turns off notifications in your apps own settings, it should be able to remove the notifications itself already. Don’t make the user need to change the app permissions alone to control the notifications.
  • This was built to look sleek, and minimal, with low effort to actually use the notifications.

Then you can send an instance into the new App inside MainActivity:

        protected override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);

            Xamarin.Essentials.Platform.Init(this, savedInstanceState);
            global::Xamarin.Forms.Forms.Init(this, savedInstanceState);
            LoadApplication(new App(new Notifier()));
        }

This should be easy to understand, we need to customise App a touch:

        public static INotify Notify { get; private set; }

        public App(INotify iNotify)
        {
            InitializeComponent();
            Notify = iNotify;

            MainPage = new MainPage();
        }

Now there’s a simple method to send a notification, but one thing I haven’t solved completely yet is the permissions. In your Android emulator (or device) got to the apps settings, and Allow Notifications.

Allow Notifications on your device/emulator

If anyone could point me in the right direction for using the popup request for the permission in Android 13, I would love the assistance.

You then just need a function you run, or call, to set up the notification. For instance, the sample uses a button press:

        private void Button_Clicked(object sender, EventArgs e)
        {
            App.Notify.SendNotification(DateTime.Now.AddSeconds(10), 100, "Test 1", "1", "1");
        }

With that, after 10 seconds on the button press, the notification shows up:

The test notification in the emulator

That being said, I can organise way better interaction with notifications for Active e-Fitness now. I just need to decide more of what I will end up using for the system as a whole.

By edg3