Windows 8 Store Apps Learning (64) Background tasks: Developing a simple background task

Source: Internet
Author: User
Tags foreach datetime execution require requires sessions tostring xmlns

Introduced

Re-imagine Windows 8 Store Apps after a task

Develop a simple background task

Example

1. Create a new background task with Windows runtime components

Backgroundtasklib/demo.cs

* * Background Task * NOTE: * Background task item output type needs to be set to "Windows runtime component", it will generate. winmd file, winmd-windows Metadata/using System;
Using System.Threading.Tasks;
Using Windows.ApplicationModel.Background;
    
Using Windows.storage;
    namespace Backgroundtasklib {//implements the Ibackgroundtask interface with only one method, that is, Run () public sealed class Demo:ibackgroundtask
            {Public async void Run (Ibackgroundtaskinstance taskinstance) {//Background task triggered when execution is terminated
    
            taskinstance.canceled + = taskinstance_canceled; Asynchronous operation, which notifies the system that the background task can continue working after the Ibackgroundtask.run method returns backgroundtaskdeferral deferral = Taskinstance.getdeferral ()
    
            ;
                try {//Specifies the progress of the background task taskinstance.progress = 0; Taskinstance.instanceid-The unique identification of the background task instance, which is generated by the system, consistent with the ibackgroundtaskregistration.taskid of the foreground//written to the relevant data Piece Storagefile file = await ApplicationData.Current.LocalFolder.CreateFileAsYnc (@ "Webabcdbackgroundtask\demo.txt", creationcollisionoption.replaceexisting);
    
                Await Fileio.writetextasync (file, "progress:0, CurrentTime:" + DateTime.Now.ToString ()); 
    
                    for (UINT progress = Progress <= progress +) {await task.delay (1000);
    
                    Updates the progress of the background task taskinstance.progress = Progress; Write related data to file = await ApplicationData.Current.LocalFolder.GetFileAsync (@ "Webabcdbackgroundtask\dem
                    O.txt "); Await Fileio.appendtextasync (file, "Progress:" + progress.
                ToString () + ", CurrentTime:" + DateTime.Now.ToString ()); Finally {//completes asynchronous operation deferral.
            Complete (); } void Taskinstance_canceled (ibackgroundtaskinstance sender, Backgroundtaskcancellationreason Reaso
      N) {      * * Backgroundtaskcancellationreason-the reason why the background task was terminated in execution * Abort-the foreground app called the Ibackgro Undtaskregistration.unregister (TRUE) * terminating-terminated * loggingoff because of System policy-user logoff system Cancelled * servicingupdate-canceled for app update *}}

2. Demo Background Task application

Backgroundtask/demo.xaml

<page
    x:class= "XamlDemo.BackgroundTask.Demo"
    xmlns= "http://schemas.microsoft.com/winfx/2006/xaml/ Presentation "
    xmlns:x=" Http://schemas.microsoft.com/winfx/2006/xaml "
    xmlns:local=" using: Xamldemo.backgroundtask "
    xmlns:d=" http://schemas.microsoft.com/expression/blend/2008 "
    xmlns:mc=" http:/ /schemas.openxmlformats.org/markup-compatibility/2006 "
    mc:ignorable=" D ">
    
    <grid background=" Transparent ">
        <stackpanel margin=" 0 0 0 ">
    
            <textblock name=" lblmsg "fontsize=" 14.667 "  / >
                
            <button name= "Btnregister" content= "Register a background task" margin= "0 0 0" click= "btnregister_click_1"/>
            <button x:name= "Btnunregister" content= "unregistered background task" margin= "0 0 0" click= "btnunregister_click_1"  / >
    
        </StackPanel>
    </Grid>
</Page>

Backgroundtask/demo.xaml.cs

* * Demo Background Task Application * * NOTE: * 1, need to refer to background task items, background task sample code in Backgroundtasklib/demo.cs * 2, need to add "background task" statement in Package.appxmanifest, and
Specify entrypoint (class full name of background task) * * Another: * For background tasks, please refer to the Introduction_to_background_tasks.docx file */using System in this directory;
Using System.Collections.Generic;
Using Windows.ApplicationModel.Background;
Using Windows.UI.Core;
Using Windows.UI.Xaml;
Using Windows.UI.Xaml.Controls;
    
Using Windows.UI.Xaml.Navigation; Namespace Xamldemo.backgroundtask {public sealed partial class Demo:page {//Registered background task name Priva
    
        Te string _taskname = "Demo"; The entrypoint of the background task that is registered, that is, the class full name of the background task//need to add a "background task" declaration in Package.appxmanifest, and specify EntryPoint as follows: <extension category= "Windows.backgroundtasks" entrypoint= "Backgroundtasklib.demo"/> private string _taskentrypoint = "BackgroundT
    
        Asklib.demo ";
    
        Whether the background task has been registered in the system private bool _taskregistered = false; Progress notes for background task execution status private string _taskprogreSS = ""; Public Demo () {this.
        InitializeComponent ();
            } protected override void Onnavigatedto (NavigationEventArgs e) {//Traverse all registered background tasks
            foreach (Keyvaluepair<guid, ibackgroundtaskregistration> task in Backgroundtaskregistration.alltasks) {if (Task).
                    Value.name = = _taskname)//NOTE: The unique identification of the background task is Ibackgroundtaskregistration.taskid, where Name is only for demonstration convenience { If a specified background task is found, it adds Progress and Completed event monitoring for the foreground app to receive progress reports and complete reports on the background tasks ATTACHPROGRESSANDC Ompletedhandlers (Task.
                    Value);
                    _taskregistered = true;
                Break
        } updateui ();
            } private void Btnregister_click_1 (object sender, RoutedEventArgs e) {//For constructing a background task
    
            Backgroundtaskbuilder builder = new Backgroundtaskbuilder (); BuilDer. Name = _taskname; The name of the background task, shown with builder. Taskentrypoint = _taskentrypoint;  Background task entry point, the class full name of background task * * Background task triggers Ibackgroundtrigger * Timetrigger-requires app On the lock screen, the minimum period of 15 minutes * Maintenancetrigger-similar to the Timetrigger, but does not require the app on the lock screen, the minimum cycle of 15 minutes, if the app is not on the lock screen, the fastest 2-hour execution         Once * Systemtrigger-generally do not require app on the lock screen * smsreceived-when new SMS messages are received *
             When Lockscreenapplicationadded-app is added to the lock screen * Lockscreenapplicationremoved-app is removed from the lock screen
             * Onlineidconnectedstatechange-When the current connected Microsoft account changes * timezonechange-time zone changes
             * Servicingcomplete-The system completes the app update * Controlchannelreset-when the control channel is reset, the app needs to be on the lock screen         * Networkstatechange-When the network state changes * Internetavailable-internet becomes available *
            Sessionconnected-session state connection, the app needs to be on the lock screen * Here the session refers to the user and the local sessions between, that is, when switching users will be changed when the meeting * userpresent-when the user becomes active, you need App on lock screen * useraway-user becomes inactive, need app on lock screen * Pushnotificationtrigger-need app in lock screen On For push notifications See: Backgroundtask/pushnotification.xaml * Controlchanneltrigger-requires the app to be on the lock screen. For "Push channel" see: Backgroundtask/controlchannel.xaml * * Builder.
    
            Settrigger (New Systemtrigger (Systemtriggertype.timezonechange, false));
             * * Background task execution condition systemconditiontype, when background task triggers are triggered, only the specified conditions are met to perform * userpresent-user is active * usernotpresent-User inactive * internetavailable-internet status is available * Internetnot Available-internet status is not available * sessionconnected-session state is connected. The session here refers to the sessions between the user and the native, which means that if a user is logged on in the system sessionconnected * sessiondisconnected-the conversation state is disconnected. The session here refers to the session between the user and the native, which means that if the system does notThere is a user login (all users are logged out) then sessiondisconnected * * * builder.
    
            Addcondition (New Systemcondition (systemconditiontype.internetavailable)); Register your system for the following backgroundtaskregistration task = Builder.
            Register (); Task. TaskId; Get the identification of the next task, a GUID//for this background task to increase Progress and Completed event monitoring so that the foreground app receives background task progress report and complete reporting Attachprog
    
            Ressandcompletedhandlers (Task);
    
            _taskregistered = true;
        UpdateUI ();
            } private void Btnunregister_click_1 (object sender, RoutedEventArgs e) {//Traverse all registered background tasks
            foreach (Keyvaluepair<guid, ibackgroundtaskregistration> task in Backgroundtaskregistration.alltasks) {if (Task).
                    Value.name = = _taskname)//NOTE: The unique identification of the background task is Ibackgroundtaskregistration.taskid, where Name is only for demonstration convenience { Logs the specified background task out of the system. The only parameter represents whether you need to cancel a task if the current background task is running. Value.unreGister (TRUE);
                Break
    
            } _taskregistered = false;
        UpdateUI (); } private void Attachprogressandcompletedhandlers (ibackgroundtaskregistration Task) {// Add Progress and Completed event monitoring for the task so that the foreground app receives the progress report of the background task and completes the reporting task.
            Progress + = new Backgroundtaskprogresseventhandler (onprogress);
        task.completed + = new Backgroundtaskcompletedeventhandler (oncompleted);
            } private void OnProgress (ibackgroundtaskregistration task, Backgroundtaskprogresseventargs args) { Gets the execution progress of the background task _taskprogress = args.
    
            Progress.tostring ();
        UpdateUI (); 
            } private void OnCompleted (ibackgroundtaskregistration task, Backgroundtaskcompletedeventargs args) {
    
            Background tasks have been completed _taskprogress = "complete";
          If there is an error in the execution of this background task, the call to Checkresult () throws an exception  try {args.
            Checkresult (); The catch (Exception ex) {_taskprogress = ex.
            ToString ();
        } updateui (); Private async void UpdateUI () {await dispatcher.runasync (coredispatcherpriority.normal
                , () => {btnregister.isenabled =!_taskregistered;
    
                btnunregister.isenabled = _taskregistered;
            if (_taskprogress!= "") Lblmsg.text = "Progress:" + _taskprogress;
        }); }
    }
}

Ok

[SOURCE Download]:http://files.cnblogs.com/webabcd/windows8.rar

See more highlights of this column: http://www.bianceng.cnhttp://www.bianceng.cn/Programming/net/

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.