Search code examples
c#uwpbackground-process

Update progress from BackgroudDownloader when app is closed


I am using BackgroundDownloader in my UWP app like:

private async void StartDownload()
{
    var destinationFile = await KnownFolders.VideosLibrary.CreateFileAsync("temp.zip", CreationCollisionOption.GenerateUniqueName);
    var backgroundDownloader = new BackgroundDownloader();
    var downloadOperation = backgroundDownloader.CreateDownload(fileUrl, destinationFile);

    SendUpdatableToastWithProgress();
    var progressCallback = new Progress<DownloadOperation>();
    progressCallback.ProgressChanged += ProgressCallback_ProgressChanged;
    var opProgress = await downloadOperation.StartAsync().AsTask(progressCallback);
}

private void ProgressCallback_ProgressChanged(object sender, DownloadOperation e)
{
    if (e.Progress.TotalBytesToReceive > 0)
    {
        var br = e.Progress.BytesReceived;
        var percent = br * 1.0 / e.Progress.TotalBytesToReceive;
        UpdateToastProgress(percent);
    }
}

Is there any chance how can I get ProgressChanged fired even the UWP App is closed?


Solution

  • There is currently no reliable option on how to update BackgroundDonwloader progress in Toast notification through Progress<DownloadOperation>.

    As per Microsoft documentation, BackgroundTask could be suspended or killed based on the actual system state. That could happen before the BackgroundDownloader finishes its job and your Toast notification will look like it got frozen.

    The best approach here is to update your Toast progress bar in the app suspended or exited event with AdaptiveProgressBarValue.Indeterminate with appropriate texting (e.g. Finishing download in background, etc.). Based on comments from @Faywang - MSFT you can still get notifications about successful or failed download even the app is closed or suspended.

    Another approach would be to use extendedExecutionUnconstrained to be able to run BackgroundTask indefinitely. In that case, you would be able to update Toast progress with 'live' data and even more, to trigger new download via BackgroundDownloader. The downside of this approach is that your app cannot be listed in Microsoft Store.