日期:2014-05-17 浏览次数:20958 次
所谓后台传输,关键是突出在,在应用程序不在前台运行时,它仍然可以进行数据传输,一般而言,这个功能用于下载文件比较适合,像“应用商店”的下载应用就是使用了后台传输。
这个后台传输当然包括下载和上传了,不过,我想是下载的情况会多一些,呵呵,不知道是不是这样,元芳,你怎么看?
好了,不管元芳怎么看了,首先大家做好心理准备,接下来我会讲一点点比较枯燥的东东,不怕,只是一点点而已,我不喜欢长篇巨论,免得各位看着看着就睡觉了。
实现后台下载,一般有以下几步要走:
这里因为涉及到操作进度,所以要使用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 (