How to Add Support for Background Transfers in your Windows Phone Application

Introduction

Today, mobile applications hardly persist data on the
devices. They get their information from the cloud. A typical example is an
application that streams YouTube videos or downloads data to work on.

Whenever there is a large file to work on, the user
experience can be dismal if the application developer does a synchronous
download of the file. The asynchronous file transfer can be a workable solution
as long as the application can let the user know that a download has been
queued and notify the user when it is complete.

Windows
Phone
“Mango” introduced support for background transfers. Let us write an
application that makes use of the "Background transfer" feature in a
Windows Phone application.

Hands-On

To start with, create a Windows Phone application titled
“WPBackgroundTransferDemo”.

Add a Button and two TextBox controls to the MainPage.xaml.
Rename the first TextBox control to “textBoxStatus”, the second TextBox to
“textBoxProgress” and the Button control to “buttonAddToTransfer”.

Add an Event for Click on the button buttonAddToTransfer. To
do this, double click the buttonAddToTransfer control on MainPage.xaml.

        private void buttonAddToTransfer_Click(object sender, RoutedEventArgs e)
        {
            Uri transferUri = new Uri(Uri.EscapeUriString("http://vipuldpatel.web.officelive.com/Documents/pictures.zip"), UriKind.RelativeOrAbsolute);

            BackgroundTransferRequest transferRequest = new BackgroundTransferRequest(transferUri);
            transferRequest.TransferStatusChanged += new EventHandler<BackgroundTransferEventArgs>(transferRequest_TransferStatusChanged);

     transferRequest.TransferProgressChanged +=new EventHandler<BackgroundTransferEventArgs>(transferRequest_TransferProgressChanged);
            transferRequest.Method = "GET";
            Uri downloadUri = new Uri("shared/transfers/pictures.zip", UriKind.RelativeOrAbsolute);
            transferRequest.DownloadLocation = downloadUri;
            IsolatedStorageFile isf = IsolatedStorageFile.GetUserStoreForApplication();
            bool exists = isf.FileExists(@"shared\transfers\pictures.zip");
            BackgroundTransferService.Add(transferRequest);

 
            exists = isf.FileExists(@"shared\transfers\pictures.zip");
        }

Here, we create an instance of BackgroundTransferRequest
class and make a “GET” HTTP request and pass in the URL from where we want to
download the file.

We also add code to wire up the “TransferStatusChanged” event
and the “TransferProgressChanged” events.

Our TransferProgressChanged event handler is very simple. It
calculates the progress of the transfer request by dividing the "Bytes Received"
by "the total bytes to be received".

        private void transferRequest_TransferProgressChanged(object sender, BackgroundTransferEventArgs e)
        {
            textBoxProgress.Text = ((e.Request.BytesReceived * 100.0) / e.Request.TotalBytesToReceive).ToString();
        }

The Transfer Status Changed event updates the status of the
request by updating the textbox.

private void transferRequest_TransferStatusChanged(object sender, BackgroundTransferEventArgs e)
        {
            Debug.WriteLine("transfer status: " + e.Request.TransferStatus.ToString());
            //Console.WriteLine(e.Request.TransferStatus.ToString());
            IsolatedStorageFile isf = IsolatedStorageFile.GetUserStoreForApplication();
            textBoxStatus.Text = e.Request.TransferStatus.ToString();
             if (e.Request.TransferStatus == TransferStatus.Completed)
                Debug.Assert(isf.FileExists(@"shared\transfers\pictures.zip") == true);
        }

Compile and run your application. When we run the
application for the first time, we see the screen shown below.

Run the application for the first time
Figure 1: Run the application for the first time

Compile and run your application

Click the “Button” control to add the background transfer
request to the queue.

Click the
Figure 2: Click the “Button” control to add the background transfer
request to the queue.

Add the background transfer request to the queue

You will notice that the transfer starts and the Status and
Progress textboxes get updated with the current status, which is “Transferring”
and the current progress.

When the transfer is complete, you will notice the Status to
be completed and Progress to be 100.

This implies that the background transfer has completed
successfully.

The background transfer has completed
Figure 3: The background transfer has completed

This was a very simple example of using the
BackgroundTransferRequest class. In a future article, we will visit the best
practices of using the BackgroundTransferRequest class.

If you are having trouble following along, you can download
the sample code below.

Summary

In this article, we learned about using the
BackgroundTransferRequest class to add an asynchronous download request in a
Windows Phone “Mango” application. I hope you have found this information
useful.

More by Author

Must Read