.NET MAUI: downloading a file in the background (Android)

rodionovid 80 Reputation points
2024-05-02T23:04:10.0233333+00:00

Hello. Is there a way to do some action in background in case of android devices? For example, in my app I have a callback that starts to download a file after user pressed the download button. This file is quite large and some devices may turn off their screens before download is completed. That leads to download reset and user has to press the button again. My callback function looks like this:

private void DownloadButton_Click(object sender, EventArgs e)
{
    try
    {
        WebClient webClient = new WebClient();
        webClient.DownloadProgressChanged += new DownloadProgressChangedEventHandler(DownloadProgressCallback);
        webClient.DownloadFileCompleted += new AsyncCompletedEventHandler(DownloadCompletedCallback);
        webClient.DownloadFileAsync(downloadUrl, downloadPath);
    }
    catch (Exception ex)
    {
        ...
    }
}

So, I want this method to execute even if user's devices screen is off. I will epriciate any help with this question.

.NET MAUI
.NET MAUI
A Microsoft open-source framework for building native device applications spanning mobile, tablet, and desktop.
2,956 questions
0 comments No comments
{count} votes

Accepted answer
  1. Yonglun Liu (Shanghai Wicresoft Co,.Ltd.) 36,706 Reputation points Microsoft Vendor
    2024-05-03T01:48:50.3833333+00:00

    Hello,

    In Android if a task needs to be executed in the background, you need to implement it as a Background Service. This is a native feature of Android, so you can refer to the following documentation and implement it in MAUI.

    This guide discusses Xamarin.Android services, which are Android components that allow work to be done without an active user interface. Services are very commonly used for tasks that are performed in the background, such as time consuming calculations, downloading files, playing music, and so on. It explains the different scenarios that services are suited for and shows how to implement them both for performing long-running background tasks as well as for providing an interface for remote procedure calls.

    Although this documentation is for Xamarin, MAUI is not different from Xamarin for the use of native features.

    Best Regards,

    Alec Liu.


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.


0 additional answers

Sort by: Most helpful