New Fashion Windows 8 Development (35): background transmission

Source: Internet
Author: User
Tags blank page

The key to the so-called background transmission is that it can still transmit data when the application is not running on the foreground. In general, this function is suitable for downloading files, download applications like the App Store use background transmission.

This background transmission includes downloading and uploading. However, I think there will be more downloads. I don't know if this is the case, Yuan Fang. What do you think?

Well, no matter how Yuan Fang reads it, first of all, everyone is prepared for it. Next, I will talk about a little boring stuff, not afraid. It's just a little bit. I don't like the long story, otherwise you may go to bed.

 

To implement background download, follow these steps:

  1. Introduce the windows. Networking. backgroundtransfer namespace.
  2. New: A backgrounddownloader (if data is downloaded) or a backgrounduploader (if data is downloaded ).
  3. For backgrounddownloader, call the createdownload method to create a downloadoperation instance. For backgrounduploader, call the createupload method to create an uploadoperation instance;
  4. Call the startasync method of downloadoperation or the startasync method of uploadoperation to start working.

The windowsruntimesystemextensions class is windows. foundation. iasyncoperationwithprogress <tresult, tprogress> defines the extension method astask. I will not go into details here. I will see the example. Haha, it is a wonderful use of C #5.0 !!

 

OK. The boring period has passed. The following is an exciting period. This example is not complicated. You can enter an MP3 file and download it.

[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 = "input download URI:" verticalalignment = "center"/> <textbox X: name = "txtinputuri" width = "680"/> <button X: Name = "btndown" margin =, 0, 0 "verticalalignment =" center "content =" start to download "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, "/> <textblock X: Name =" tbmsg "margin =", "/> </stackpanel> </GRID> </Page>

Among them, progressbar is certainly used to display the progress, other controls, it is estimated that you are familiar with 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; US Ing windows. storage; using Windows. storage. pickers; using Windows. storage. streams; namespace app1 {/// <summary> /// you can use it to itself or navigate to a blank page inside the frame. /// </Summary> Public sealed partial class mainpage: Page {public mainpage () {This. initializecomponent ();} private async void ondownload_click (Object sender, routedeventargs e) {// determine whether the downloaded Uri has been input if (string.isnullorwhitespace(this.txt inputuri. text) return; // select the file storage location filesavepicker picker = new filesavepicker (); picker. filetypechoices. add ("MP3 file", new string [] {". MP3 "}); storagefile file = Await picker. picksavefileasync (); If (file! = NULL) {// instantiate backgrounddownloader downloader = new backgrounddownloader (); downloadoperation operation = Downloader. createdownload (New uri(this.txt inputuri. text), file); // progress SS <downloadoperation> progressdown = new progress <downloadoperation> (this. progresschanged); // starts to download btndown. isenabled = false; var opresult = await operation. startasync (). astask (progressdown); BT Ndown. isenabled = true; // determine the download result switch (opresult. Progress. Status) {Case backgroundtransferstatus. Completed: tbmsg. Text = "download completed. "; Break; Case backgroundtransferstatus. Error: tbmsg. Text =" An error occurred while downloading. "; Break; default: tbmsg. Text =" unknown. "; Break ;}}/// <summary >/// report progress /// </Summary> private async void progresschanged (downloadoperation OP) {var P = op. progress; Double T = P. totalbytestoreceive; // The total number of bytes to download. Double D = P. bytesreceived; // number of received bytes // calculated percentage of completed bytes. Double PC = D/T * 100; await dispatcher. runasync (windows. UI. core. coredispatcherpriority. normal, () => {This. probar. value = pc; this. tbmsg. TEXT = string. format ("downloaded {0} Bytes/total {1} characters Section. ", D. tostring (" N0 "), T. tostring (" N0 "));});}}}

You may ask, why do you want to use the progress <t> class?

You think, the startasync method asynchronously calls back the downloadoperation object, but you guess when it will return? It is not returned until the entire file is downloaded. Then, you still report the progress of a bird. Is that true?

When you use progress <t>, you can send a delegate to the progresschanged event. To put it bluntly, you can handle this event so that you can report the progress in real time. Is this true for Yuan Fang?

 

After the program is completed, it is to run the test. Find an MP3 post and click "Start download" to see if it works? If there is no error, you will see the content shown in.

 

 

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.