dotnet / docs-maui

This repository contains documentation for .NET Multi-platform App UI (MAUI).
https://docs.microsoft.com/dotnet/maui
Creative Commons Attribution 4.0 International
223 stars 194 forks source link

MAUI Android Background Task Documentation missing #2276

Open SeppPenner opened 4 months ago

SeppPenner commented 4 months ago

Description

Since there is https://github.com/dotnet/maui/issues/19041 for iOS, I wanted to ask how background service in an app would run in MAUI for Android.

My tries so far.

  1. Add the Microsoft.Extensions.Hosting NuGet package and try to run it as BackgroundService as for ASP.Net (As described here https://learn.microsoft.com/en-US/dotnet/architecture/microservices/multi-container-microservice-net-applications/background-tasks-with-ihostedservice), e.g.
builder.Services.AddSingleton<DataQueueService>();
builder.Services.AddHostedService(p => p.GetRequiredService<DataQueueService>());

--> Doesn't work, service is never executed. :collision:

  1. Implement it as it was done in Xamarin like described in https://learn.microsoft.com/en-us/previous-versions/xamarin/android/app-fundamentals/services/creating-a-service/.

--> Doesn't work, the [Service] attribute and the Service class do not exist. :collision:

  1. Following https://github.com/dotnet/maui/issues/20678 and https://github.com/alzubitariq/MauiAppServiceIssue, I tried to add the service as following:
#if ANDROID
        builder.Services.AddSingleton<IDataQueueService, DataQueueService>();
#endif

and implemented the service like this:

public interface IDataQueueService
{
    Task Start();
    Task Stop();
}

and

public sealed class DataQueueService : IDataQueueService
{
    private readonly CancellationTokenSource cancellationTokenSource = new();

    public Task Start()
    {
        _ = this.Execute();
        return Task.CompletedTask;
    }

    public Task Stop()
    {
        this.cancellationTokenSource.Cancel();
        return Task.CompletedTask;
    }

    private async Task Execute()
    {
        while (!this.cancellationTokenSource.IsCancellationRequested)
        {
            // Todo: Something more useful here.
            Console.WriteLine("Mane");
            await Task.Delay(5000);
        }

        // Todo: Something more useful here.
        Console.WriteLine("Mane2");
    }
}

and in the MainPage.xaml.cs in the constructor:

    public MainPage()
    {
        this.InitializeComponent();

#if ANDROID
        var services = Application.Current?.MainPage?.Handler?.MauiContext?.Services;

        if (services is not null)
        {
            var backgroundService = services.GetService<IDataQueueService>();

            if (backgroundService is not null)
            {
                backgroundService.Start();
            }
        }
#endif
    }

--> Seems to work, but not sure if background services should be used like this. 😕

Any advice / documentation on how to do this with MAUI on Android would be nice.

Steps to Reproduce

Check above.

Link to public reproduction project repository

No response

Version with bug

8.0.40 SR5

Is this a regression from previous behavior?

Not sure, did not test other versions

Last version that worked well

Unknown/Other

Affected platforms

Android

Affected platform versions

No response

Did you find any workaround?

Solution 3 seems to work, but not sure if this i correct. + This should get documented somewhere...

Relevant log output

wasm-tools                    8.0.5/8.0.100          VS 17.9.34902.65
ios                           17.2.8004/8.0.100      VS 17.9.34902.65
maui-windows                  8.0.7/8.0.100          VS 17.9.34902.65
android                       34.0.52/8.0.100        VS 17.9.34902.65
maccatalyst                   17.2.8004/8.0.100      VS 17.9.34902.65
github-actions[bot] commented 4 months ago

Hi I'm an AI powered bot that finds similar issues based off the issue title.

Please view the issues below to see if they solve your problem, and if the issue describes your problem please consider closing this one and thumbs upping the other issue to help us prioritize it. Thank you!

Closed similar issues:

Note: You can give me feedback by thumbs upping or thumbs downing this comment.