新時尚Windows8開發(35):後台傳輸

來源:互聯網
上載者:User

所謂後台傳輸,關鍵是突出在,在應用程式不在前台運行時,它仍然可以進行資料轉送,一般而言,這個功能用於下載檔案比較適合,像“市集”的下載應用就是使用了後台傳輸。

這個後台傳輸當然包括下載和上傳了,不過,我想是下載的情況會多一些,呵呵,不知道是不是這樣,元芳,你怎麼看?

好了,不管元芳怎麼看了,首先大家做好心理準備,接下來我會講一點點比較枯燥的東東,不怕,只是一點點而已,我不喜歡長篇巨論,免得各位看著看著就睡覺了。

 

實現後台下載,一般有以下幾步要走:

  1. 引入Windows.Networking.BackgroundTransfer命名空間。
  2. new一個BackgroundDownloader(如果下載資料)或者一個BackgroundUploader(如果是下載)。
  3. 如果是BackgroundDownloader,就調用CreateDownload方法建立DownloadOperation執行個體,如果是BackgroundUploader,就調用CreateUpload方法建立UploadOperation執行個體;
  4. 此時調用DownloadOperation的StartAsync方法或者UploadOperation的StartAsync方法開始幹活。

這裡因為涉及到操作進度,所以要使用WindowsRuntimeSystemExtensions類為Windows.Foundation.IAsyncOperationWithProgress<TResult, TProgress>所定義的擴充方法AsTask,這個我不深入講了,看看例子就知道,呵呵,那可是C# 5.0的妙用!!

 

OK,枯燥期已過,下面是激情期,這個例子不複雜,就是輸入一個MP3的,然後下載。

【XAML】

<Page    x:Class="App1.MainPage"    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"    xmlns:local="using:App1"    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"    mc:Ignorable="d">        <Page.Resources>        <Style TargetType="TextBlock">            <Setter Property="FontSize" Value="27"/>            <Setter Property="FontFamily" Value="宋體"/>        </Style>    </Page.Resources>    <Grid Background="{StaticResource ApplicationPageBackgroundThemeBrush}">        <Grid.RowDefinitions>            <RowDefinition Height="auto"/>            <RowDefinition Height="*"/>        </Grid.RowDefinitions>        <StackPanel Grid.Row="0" Margin="15,8" Orientation="Horizontal">            <TextBlock Text="輸入下載URI:" VerticalAlignment="Center" />            <TextBox x:Name="txtInputUri" Width="680"/>            <Button x:Name="btnDown" Margin="38,0,0,0" VerticalAlignment="Center" Content="開始下載" Padding="17,5,17,5" FontSize="22" Click="onDownload_Click"/>        </StackPanel>        <StackPanel Grid.Row="1" Margin="20">            <ProgressBar x:Name="probar" Maximum="100" Minimum="0" SmallChange="1" Width="700" HorizontalAlignment="Left" Foreground="Yellow"                         Height="30" Margin="6,21,0,35"/>            <TextBlock x:Name="tbMsg" Margin="6,8,0,0" />        </StackPanel>    </Grid></Page>

其中,ProgressBar當然是用來顯示進度了,其它控制項,估計各位是N + 6的熟悉了。

 

【C#】

using System;using System.Collections.Generic;using System.IO;using System.Linq;using Windows.Foundation;using Windows.Foundation.Collections;using Windows.UI.Xaml;using Windows.UI.Xaml.Controls;using Windows.UI.Xaml.Controls.Primitives;using Windows.UI.Xaml.Data;using Windows.UI.Xaml.Input;using Windows.UI.Xaml.Media;using Windows.UI.Xaml.Navigation;//using Windows.Networking.BackgroundTransfer;using Windows.Storage;using Windows.Storage.Pickers;using Windows.Storage.Streams;namespace App1{    /// <summary>    /// 可用於自身或導航至 Frame 內部的空白頁。    /// </summary>    public sealed partial class MainPage : Page    {        public MainPage()        {            this.InitializeComponent();        }        private async void onDownload_Click(object sender, RoutedEventArgs e)        {            // 判斷是否已輸入下載URI            if (string.IsNullOrWhiteSpace(this.txtInputUri.Text)) return;            // 選擇檔案儲存位置            FileSavePicker picker = new FileSavePicker();            picker.FileTypeChoices.Add("MP3檔案", new string[] { ".mp3" });            StorageFile file = await picker.PickSaveFileAsync();            if (file != null)            {                // 執行個體化BackgroundDownloader                BackgroundDownloader downloader = new BackgroundDownloader();                DownloadOperation operation = downloader.CreateDownload(new Uri(this.txtInputUri.Text), file);                // 進度                Progress<DownloadOperation> progressDown = new Progress<DownloadOperation>(this.ProgressChanged);                // 開始下載                btnDown.IsEnabled = false;                var opresult = await operation.StartAsync().AsTask(progressDown);                btnDown.IsEnabled = true;                // 判斷下載結果                switch (opresult.Progress.Status)                {                    case BackgroundTransferStatus.Completed:                        tbMsg.Text = "下載已完成。";                        break;                    case BackgroundTransferStatus.Error:                        tbMsg.Text = "下載過程中發生了錯誤。";                        break;                    default:                        tbMsg.Text = "未知。";                        break;                }            }         }        /// <summary>        /// 報告進度        /// </summary>        private async void ProgressChanged(DownloadOperation op)        {            var p = op.Progress;            double t = p.TotalBytesToReceive;//要下載總位元組數            double d = p.BytesReceived;//已接收位元組數            // 計算完成百分比            double pc = d / t * 100;            await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>                {                    this.probar.Value = pc;                    this.tbMsg.Text = string.Format("已下載{0}位元組/共{1}位元組。", d.ToString("N0"), t.ToString("N0"));                });        }    }}

你可能會問,幹嗎要用Progress<T>類?

你想啊,StartAsync方法非同步呼叫返回DownloadOperation對象,可是,你猜猜它是啥時候才能返回?還不是要等到整個檔案下載完了它才返回,那麼一來,你還報告個鳥進度,是不是這樣呢?

而使用Progress<T>,可以傳一個委託給ProgressChanged事件,說白了,就是處理這個事件,這樣一來才能即時報告進度,元芳,是不是這樣呢?

 

程式弄好之後,就是運行測試,隨便找個MP3的帖上去,然後點擊“開始下載”,看有沒有效果?如果無誤,你會看到如所示的內容。

 

 

 

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.