loury Pe
loury Pe

Reputation: 25

How to make a Net MAui app run in the background?

I am new to the NET MAUI mobile app development. I'm creating an app that scans for wifi networks nearby, and if it finds a particular network, it has to do some operations. I want this app to work even in the background, continuing to update the list of networks found and run the method I created.

How can this be done?

Upvotes: 1

Views: 1117

Answers (2)

Yanshof
Yanshof

Reputation: 9926

NET MAUI itself doesn't directly support background services that run independently of the app. This is because the concept of background services in ASP.NET Core (= BackgroundService) doesn't translate well to a client application lifecycle.

Upvotes: 0

If your purpose is not to block the UI while scanning the networks, you can simply use async/await. Consider the following simplified code example:

class WifiNetworkViewModel : ViewModelBase
{
    public WifiNetworkViewModel()
    {
        Networks = new ObservableCollection<WifiNetwork>();
    }

    public ObservableCollection<WifiNetwork> Networks { get; }

    public async Task ScanWifiNetworks()
    {
        while (true)
        {
            // Scanning logic here (use await)
            // When found one, add it to the Networks collection
            Networks.Add(new WifiNetwork { Name = "Wifi Network 1" });
            // Break the while loop with timeout etc.
        }
    }
}

class WifiNetwork
{
    public string Name { get; set; }
}

To use this view model, I assume you have a list control such as ListView and bind it to the Networks property like

<ListView ItemsSource="{Binding Networks}"/>

When a found network is added to the Networks property then the ListView will populate automatically. To start scanning, call the ScanWifiNetworks() method from a Button for example.

Upvotes: -1

Related Questions