BackgroundTransfer API

The BackgroundTransfer API in Universal Windows Platform (UWP) allows your application to perform file uploads and downloads in the background, even when the app is not actively running. This is crucial for tasks like downloading large files, syncing data, or uploading user-generated content without interrupting the user experience.

Overview

The BackgroundTransfer class is the primary entry point for managing background transfer operations. It provides methods to create, manage, and retrieve transfer groups, which are collections of related upload and download operations.

Key concepts include:

  • Transfer Groups: A logical grouping of transfer operations. This helps in managing and querying related transfers.
  • Transfer Operations: Individual upload or download tasks.
  • Progress Tracking: The API provides mechanisms to monitor the progress, status, and bytes transferred for each operation.
  • Error Handling: Robust error reporting for failed transfers.
  • System Integration: Leverages the operating system to manage transfers efficiently, conserving battery and network resources.

Classes

Class Description
BackgroundTransfer Provides access to background transfer functionality, including creating and managing transfer groups.
BackgroundTransferGroup Represents a collection of related background transfer operations.
DownloadOperation Represents a single background file download operation.
UploadOperation Represents a single background file upload operation.
BackgroundTransferStatus Enumeration that defines the possible states of a transfer operation.

Getting Started

To use the BackgroundTransfer API, you typically need to:

  1. Request the Internet (Client) capability in your app's manifest.
  2. Access the BackgroundTransfer class.
  3. Create or retrieve a BackgroundTransferGroup.
  4. Create a DownloadOperation or UploadOperation within the group.
  5. Start the operation and monitor its progress.

Example: Downloading a File


using Windows.Networking.BackgroundTransfer;
using Windows.Storage;
using System;
using System.Threading.Tasks;

public async Task StartDownloadAsync(string url, string fileName)
{
    try
    {
        StorageFile destinationFile = await ApplicationData.Current.LocalFolder.CreateFileAsync(fileName, CreationCollisionOption.ReplaceExisting);
        Uri sourceUri = new Uri(url);

        BackgroundTransferGroup transferGroup = BackgroundTransferManager.CreateTransferGroup("MyDownloads");
        
        DownloadOperation downloadOp = new DownloadOperation(sourceUri, destinationFile, transferGroup);

        // Register for progress and completion notifications
        downloadOp.Progress += DownloadProgressHandler;
        downloadOp.Completed += DownloadCompletedHandler;

        await downloadOp.StartAsync();
    }
    catch (Exception ex)
    {
        // Handle exceptions
        System.Diagnostics.Debug.WriteLine($"Download error: {ex.Message}");
    }
}

private void DownloadProgressHandler(DownloadOperation sender, DownloadOperationProgress progress)
{
    double percent = 100.0 * progress.BytesReceived / progress.TotalBytesToReceive;
    System.Diagnostics.Debug.WriteLine($"Download Progress: {percent:F2}%");
}

private void DownloadCompletedHandler(DownloadOperation sender, BackgroundTransferEventArgs args)
{
    if (args.Operation.IsSuccessful)
    {
        System.Diagnostics.Debug.WriteLine($"Download completed: {args.Operation.ResultFile.Name}");
    }
    else
    {
        System.Diagnostics.Debug.WriteLine($"Download failed: {args.Operation.StatusCode}");
    }
}
                

Common Scenarios

Resuming Downloads

When your app is launched or resumed, you can retrieve existing download operations from the system:


var operations = await BackgroundTransfer.Current.GetDownloadsAsync();
foreach (var op in operations)
{
    // Re-attach handlers if needed
    op.Progress += DownloadProgressHandler;
    op.Completed += DownloadCompletedHandler;
}
                

Uploads

Uploading files follows a similar pattern using UploadOperation.


using Windows.Networking.BackgroundTransfer;
using Windows.Storage;
using System;
using System.Threading.Tasks;

public async Task StartUploadAsync(StorageFile fileToUpload, string uri)
{
    try
    {
        Uri serverUri = new Uri(uri);
        BackgroundTransferGroup transferGroup = BackgroundTransferManager.CreateTransferGroup("MyUploads");

        UploadOperation uploadOp = new UploadOperation(serverUri, fileToUpload, transferGroup);

        uploadOp.Progress += UploadProgressHandler;
        uploadOp.Completed += UploadCompletedHandler;

        await uploadOp.StartAsync();
    }
    catch (Exception ex)
    {
        System.Diagnostics.Debug.WriteLine($"Upload error: {ex.Message}");
    }
}

// Handlers for upload progress and completion would be similar to download handlers.
                
Best Practice: Always handle the Completed event to ensure your app knows the final outcome of a transfer and can clean up resources or notify the user appropriately.

See Also