Free Trial

Safari Books Online is a digital library providing on-demand subscription access to thousands of learning resources.

  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • PrintPrint
Share this Page URL
Help

13. Windows Phone 7 > Using the background transfer service

Using the background transfer service

Using the background transfer service Downloading files on a mobile device can be time-consuming. A slow Wi-Fi connection or bad 3G coverage are all still too common. While downloading a file, the application doing the download needs to remain the active application because of the way the application lifecycle on WP7 works. With the release of Windows Phone 7.5, a service named the BackgroundTransferService was added. This service, managed by the operating system itself, can be consumed by a WP7 application to upload and download files in the background, even after the application that started the transfer has been shut down. In this recipe, we'll extend the BluRayCollector application once more to download and play a movie trailer. Getting ready For this recipe, a starter solution is available with the downloads of the book. It can be found in the Chapter13/BluRayCollector_BackgroundService_Starter folder. The finished solution for this recipe can be found in the BluRayCollector_BackgroundService_Completed folder. How to do it... The BluRayCollector application is extended with a new feature: allowing the user to view the most popular movie trailer. Since movie trailers tend to get quite large, the download may take some time. Instead of forcing the user to leave the BluRayCollector application open and wait for the download to finish, we are going to use the BackgroundTransferService class to download the file. In the following steps, we are using this class: Open the starter solution as outlined in the Getting ready section.In the BluRayOverview.xaml page, which contains the Panorama control, we start by adding a new PanoramaItem. On this PanoramaItem, we add a Button to initiate the download, a TextBlock to show the download status and another Button to start playing the trailer after the download is finished. The latter is not enabled initially, since nothing can be played yet. The code for this is as follows: <controls:PanoramaItem Header="Popular Trailer"> <StackPanel> <Button Name="DownloadTrailerButton" Click="DownloadTrailerButton_Click" Content="Download trailer" HorizontalAlignment="Center" VerticalAlignment="Top" Height="80"> </Button> <TextBlock Name="StatusTextBlock" Text="Waiting..." HorizontalAlignment="Center"> </TextBlock> <Button Name="StartPlayingButton" IsEnabled="False" Click="StartPlayingButton_Click" Content="Start playing" HorizontalAlignment="Center" VerticalAlignment="Top" Height="80"> </Button> </StackPanel> </controls:PanoramaItem> Switch to the code-behind, BluRayOverview.xaml.cs. When clicking the Download button, we want to initiate the transfer. This is done by creating a BackgroundTransferRequest instance. To the constructor of this class, we pass two Uri instances. The first one is the Uri pointing to the file we want to download. The second one indicates where the downloaded file should be placed. Downloads done using a BackgroundTransferRequest will always be placed in a subdirectory of the Isolated Storage named shared/transfers. We can then pass the BackgroundTransferRequest to the BackgroundTransferService, which will take care of downloading the file. This is shown in the following code: private void DownloadTrailerButton_Click(object sender, RoutedEventArgs e) { using (IsolatedStorageFile isolatedStorageFile = IsolatedStorageFile.GetUserStoreForApplication()) { if (isolatedStorageFile.FileExists(downloadLocation)) { isolatedStorageFile.DeleteFile(downloadLocation); } } backgroundTransferRequest = new BackgroundTransferRequest (trailerUri, downloadLocationUri); BackgroundTransferService.Add(backgroundTransferRequest); } Note that the preceding code checks if the file is already downloaded. If so, we delete it in this scenario. An alternative might be using the already downloaded file and thus skipping the download.On the instance of the BackgroundTransferRequest, we register for events raised by the object. In this case, we register for the TransferProgressChanged and the TransferStatusChanged events. We can also pass preferences as to when the download should be allowed or disallowed (for example we can specify to only allow the download if a Wi-Fi is available). The following code should be inserted before adding the request to the service: backgroundTransferRequest.TransferPreferences = TransferPreferences.AllowCellularAndBattery; backgroundTransferRequest.TransferProgressChanged += new EventHandler<BackgroundTransferEventArgs> (backgroundTransferRequest_TransferProgressChanged); backgroundTransferRequest.TransferStatusChanged += new EventHandler<BackgroundTransferEventArgs> (backgroundTransferRequest_TransferStatusChanged); The handler of the TransferProgessChanged event will be called whenever progress is made in the download of the file. In this case, we handle this by updating the StatusTextBlock. This is shown in the following code: void backgroundTransferRequest_TransferProgressChanged (object sender, BackgroundTransferEventArgs e) { string progressText = string.Empty; if (backgroundTransferRequest != null) { progressText = String.Format ("Downloaded {0} bytes of {1} bytes", backgroundTransferRequest.BytesReceived, backgroundTransferRequest.TotalBytesToReceive); } StatusTextBlock.Text = progressText; } The BackgroundTransferEventArgs have quite a few properties available that contain information on the download in progress. Here we are using the BytesReceived (reflecting how many bytes were already downloaded) and the TotalBytesToReceive (indicating the total size of the download at hand).The TransferStatusChanged event will be called whenever the status of the transfer is updated. This happens quite a few times. The TransferStatus enumeration has statuses including None, Transferring, Waiting, Completed, and so on. In our code, we want to react to the Completed status, since then, the StartPlayingButton can be enabled. When the status is Completed, however, we still need to check the StatusCode value. The latter should be 200 or 206, which both indicate a successful transfer. If an error occurred, we display it in the StatusTextBlock. We also call the RemoveRequest() method, which will remove BackgroundTransferRequest from the download queue. Finally, we set the StartPlayingButton enabled. This can be seen in the following code: void backgroundTransferRequest_TransferStatusChanged (object sender, BackgroundTransferEventArgs e) { string statusText = string.Empty; if (backgroundTransferRequest.TransferStatus == TransferStatus.Completed) { if (backgroundTransferRequest.StatusCode == 200 || backgroundTransferRequest.StatusCode == 206) { statusText = String.Format("Status: {0}", backgroundTransferRequest.TransferStatus); RemoveRequest(backgroundTransferRequest); } else { statusText = String.Format("Status: {0}", backgroundTransferRequest.TransferError.Message); } } StartPlayingButton.IsEnabled = (backgroundTransferRequest.TransferStatus == TransferStatus.Completed); StatusTextBlock.Text = statusText; } The code for the RemoveRequest() method is shown next. Note that we as the developer are responsible for removing requests from the service. The fact that a download has completed does not remove it automatically. private void RemoveRequest (BackgroundTransferRequest backgroundTransferRequest) { BackgroundTransferService. Remove(backgroundTransferRequest); } When the movie trailer is downloaded, we can start playing it. This is done using the following code, which is called when the StartPlayingButton is clicked: private void StartPlayingButton_Click (object sender, RoutedEventArgs e) { MediaPlayerLauncher mediaPlayerLauncher = new MediaPlayerLauncher() { Media = downloadLocationUri, Location = MediaLocationType.Data }; mediaPlayerLauncher.Show(); } If we had exited the application while it was downloading the file, the download would have continued in the background. The file is transferred to the shared/transfers subdirectory of the isolated storage and will at some point be available for the application to use. How it works... Starting with Windows Phone 7.5 (SDK 7.1), a new service was added to the Windows Phone OS: the BackgroundTransferService. This service can be seen as a queue for uploads and downloads, managed and owned by the OS itself. Applications can add requests to the service in the form of a BackgroundTransferRequest. Whereas before, a download was to be done directly from application code (thus forcing the user to keep the application open while the download was taking place), it is now done outside of the application, entirely managed by the BackgroundTransferService. This results in the fact that transfers can continue, even after the application has been closed. Even after a reboot of the Windows Phone OS, the transfers will be resumed. Files that are downloaded are placed inside a subdirectory named shared/transfers of the Isolated Storage. When files are uploaded, they should be in that same directory. Restrictions Of course, transferring large files on a mobile OS can be dangerous. Without the necessary precautions, the user may be faced with huge bills because he or she transferred too much data. Also, transferring files uses a lot more power of the device. To prevent background transfers from undermining the overall user experience, several restrictions are built in. The following is a list of some restrictions; visit http://msdn.microsoft.com/en-us/library/hh202955(v=VS.92).aspx for the entire list: A file that is to be uploaded should not be larger than 5 MB.If on cellular, a file to be transferred can't be larger than 20 MB.An application may only have five outstanding requests in the queue. In code, we should check that we aren't passing this limit.All applications together on the device shouldn't have more than 500 outstanding transfers.

  

You are currently reading a PREVIEW of this book.

                                                                                                                    

Get instant access to over $1 million worth of books and videos.

  

Start a Free Trial


  
  • Safari Books Online
  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • PrintPrint