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.



About the Author

Vipul Vipul Patel

Vipul Patel is a Software Engineer currently working at Microsoft Corporation, working in the Office Communications Group and has worked in the .NET team earlier in the Base Class libraries and the Debugging and Profiling team. He can be reached at vipul_d_patel@hotmail.com

Downloads

Comments

  • There are no comments yet. Be the first to comment!

Leave a Comment
  • Your email address will not be published. All fields are required.

Top White Papers and Webcasts

  • Information is data with context. The era of Big Data has begun demonstrating to information security that there is more that can, and must, be done to identify threats, reduce risk, address fraud, and improve compliance monitoring activities by bringing better context to data and thereby creating information for actionable intelligence. This analyst report sets the stage and provides insights into IT and information security practitioners' perceptions of the impediments to, and the solutions necessary for, …

  • On-demand Event Event Date: September 10, 2014 Modern mobile applications connect systems-of-engagement (mobile apps) with systems-of-record (traditional IT) to deliver new and innovative business value. But the lifecycle for development of mobile apps is also new and different. Emerging trends in mobile development call for faster delivery of incremental features, coupled with feedback from the users of the app "in the wild." This loop of continuous delivery and continuous feedback is how the best mobile …

Most Popular Programming Stories

More for Developers

RSS Feeds