Configure a background service in .NET 8 MAUI for Windows

135 Views Asked by At

In my .NET 8 MAUI application for Windows, I would like to receive push notifications even when the app is closed. For that, I tried to add a background task using this code:

private async void RegisterBackgroundTask()
{
    var builder = new BackgroundTaskBuilder();
    builder. Name = "PushNotificationBackgroundTask";
    builder.SetTrigger(new PushNotificationTrigger());
    builder. Register();
}

Then, I registered the function in the OnLaunched function:

protected override async void OnLaunched(LaunchActivatedEventArgs args)
{
    base.OnLaunched(args);
    RegisterBackgroundTask();
}

When I run the application, I get this error

System.ArgumentException: 'Value does not fall within the expected range.'

enter image description here

I tried to set some Capabilities like that but not luck

enter image description here

So, I tried to move the background service in a different class

public sealed class PushBackgroundTask : IBackgroundTask
{
    private const string TASK_NAME = "notif_push_task";

    public static void Register()
    {
        BackgroundTaskBuilder builder = new BackgroundTaskBuilder();

        builder.TaskEntryPoint = typeof(PushBackgroundTask).FullName;
        builder.Name = TASK_NAME;
        builder.SetTrigger(new PushNotificationTrigger());
        BackgroundTaskRegistration task = builder.Register();
    }
}

and then add in the Declarations a Background Tasks like that

enter image description here

but in this case, I get another error

DEP0700: Registration of the app failed. [0x80080204] error 0x80080204: App manifest validation error: Line 49, Column 12, Reason: If it is not an audio background task, it is not allowed to have EntryPoint="LanguageInUse.Platforms.Windows.PushBackgroundTask" without ActivatableClassId in windows.activatableClass.inProcessServer.

As a side note, the implementation of Push notifications in MAUI and Azure Notification Hub is a nightmare.

How can I fix this code? What Capabilities, Declarations or permissions do I have to add?

0

There are 0 best solutions below