初识Windows 10 UWP Background Task

需要在一天之内学习backgroundTask并且demo一下,查看了微软官网,大概知道怎么做,但是对于backgroundTask还是一头雾水。找到了tutorialspoint, 思路马上清晰了很多。因为也在学习英语,顺便就把文章翻译一下。

原文地址:

https://www.tutorialspoint.com/windows10_development/windows10_development_background_execution.htm

其中原文的SendToast 函数中GetElementsByTagName参数写错了,应该为Text.

button_Click获取了状态后应该适当做处理。


The UniversalWindows Platform (UWP) introduces new mechanisms, which allow the applicationsto perform some functionality while the application is not running in theforeground. UWP also increases the ability of the applications to extend theirexecution time in the background for BackgroundTasks and Triggers. Background execution is the real complementary tail tothe application lifecycle.

通用windows平台(UWP)引入了这样一种新机制,当应用程序没有在前台运行时,允许其执行一些功能。UWP也为后台任务和触发器在后台增加了延长执行时间的能力。后台执行是应用程序生命周期一个真正的补充。

Important features of Background Tasks are –

·       A background task is triggeredby a system or time event and can be constrained by one or more conditions.

·       When a background task istriggered, its associated handler runs and performs the work of the backgroundtask.

·       A background task can run evenwhen the app that registered the background task is suspended.

·       They are part of the standardapplication platform and essentially provide an app with the ability toregister for a system event (trigger). When that event occurs, they run apredefined block of code in the background. System triggers include events suchas changes in network connectivity or the system time zone.

·       Background Execution is notguaranteed, so it is not suitable for critical functions and features.

·       The OS has a limitation as tohow many background tasks can run at the same time. So even when trigger isfired and conditions are met, the task can still not run.

后台任务的重要特点--

·       一个后台任务是由系统或者时间事件触发并且可以由一个或者多个条件来限制。

·       当一个后台任务被触发,它关联的处理器运行且执行后台任务的工作。

·       甚至当注册了这个后台任务的APP暂停时,这个后台任务还是可以执行。

·       他们是标准应用程序平台的一部分并且很关键地提供应用注册系统事件(触发器)的能力。当这些系统事件发生了,他们在后台运行一段预定义的代码。系统触发器包括事件比如像网络连接的改变或者系统时区的改变。

·       后台执行并不是保证的,因此它并不适合于关键的功能及特征。

·       关于多少个后台任务可以在同一时间执行,操作系统有限制。因此在某些情况下,尽管触发器触发了并且条件满足的情况,任务可能任然不能执行。

Create and Register Background Task

Create a background task class and register it to run whenyour app is not in the foreground. You can run code in the background bywriting classes that implement the IBackgroundTask interface. The following sample codeshows a very basic starting point for a background task class.

You can request access for background task as follows.

To build and register the background task, use the followingcode.

创建和注册后台任务:

当你的应用程序不在前台时,创建一个后台任务类并且注册运行它。你可以运行后台的代码通过写一些实现IBackgroundTask 接口的类。下面的例子代码显示一个后台任务类一个非常基础的开始。

publicsealedclassMyBackgroundTask:IBackgroundTask{
   publicvoidRun(IBackgroundTaskInstance taskInstance){
      // write code 
   }
}

你可以请求一个后台任务的可用状态。

var access = await BackgroundExecutionManager.RequestAccessAsync();
 
  
switch(access){
 
  
   caseBackgroundAccessStatus.Unspecified:
      break;
   caseBackgroundAccessStatus.AllowedMayUseActiveRealTimeConnectivity:
      break;
   caseBackgroundAccessStatus.AllowedWithAlwaysOnRealTimeConnectivity:
      break;
   caseBackgroundAccessStatus.Denied:
      break;
   default:
      break;
}

生成和注册后台任务。

var task =newBackgroundTaskBuilder{
   Name="My Task",
   TaskEntryPoint=typeof(BackgroundStuff.MyBackgroundTask).ToString()
};
 
var trigger =newApplicationTrigger();
task.SetTrigger(trigger);  
task.Register();
 
await trigger.RequestAsync();

Let us understand a simple example of backgroundtask by following all the below given steps.

下面给出的步骤可以让我们理解一个简单的后台任务。

Create a new blank UWP project ‘UWPBackgroundDemo’ and add one button in the XAML file.

创建一个空的UWP项目” UWPBackgroundDemo”并能在XAML文件中添加一个按钮。

<Page
   x:Class="UWPBackgroundDemo.MainPage"
   xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
   xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
   xmlns:local="using:UWPBackgroundDemo"
   xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
   xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
   mc:Ignorable="d">
         
   <GridBackground="{ThemeResource ApplicationPageBackgroundThemeBrush}">
      <Buttonx:Name="button"Content="Button"
         HorizontalAlignment="Left"Margin="159,288,0,0"
         VerticalAlignment="Top"Click="button_Click"/>
   </Grid>
         
</Page>

Given below is the button click event implementation in which thebackground task is registered.

下面给出的按钮点单击事件,在事件中注册吧BackGroundTask。

usingSystem;

 

usingWindows.ApplicationModel.Background;

usingWindows.UI.Xaml;

usingWindows.UI.Xaml.Controls;

 

// The Blank Page item template is documented at

   http://go.microsoft.com/fwlink/?LinkId=402352&clcid=0x409 

 

namespaceUWPBackgroundDemo{

 

   /// <summary>

      /// An empty page that can be used onits own or navigated to within a Frame.

   /// </summary>

        

   publicsealedpartialclassMainPage:Page{

 

      publicMainPage(){

         this.InitializeComponent();

      } 

                

      private async void button_Click(object sender,RoutedEventArgs e){

         var access = await BackgroundExecutionManager.RequestAccessAsync();

                  

         switch(access){

            caseBackgroundAccessStatus.Unspecified:

               break;

            caseBackgroundAccessStatus.AllowedMayUseActiveRealTimeConnectivity:

               break;

            caseBackgroundAccessStatus.AllowedWithAlwaysOnRealTimeConnectivity:

               break;

            caseBackgroundAccessStatus.Denied:

               break;

            default:

               break;

         }

                         

         var task =newBackgroundTaskBuilder{ 

            Name="My Task",

            TaskEntryPoint=typeof(BackgroundStuff.MyBackgroundTask).ToString()

         };

                         

         var trigger =newApplicationTrigger();

         task.SetTrigger(trigger); 

                         

         var condition =newSystemCondition(SystemConditionType.InternetAvailable); 

         task.Register();

                         

         await trigger.RequestAsync();

      }

   }

}

Now createanother project, but this time select Windows Runtime Component (UniversalWindows) from the menu and give the name Backgroundstuff to this project.

现在创建另一个项目,但是这次选择 Windows Runtime Component(Universal Windows) .


Given below isthe C# code. which contains MyBackgroundTask class implantation and it will run thebackground task.

给出下面c#代码,实现MyBackgroundTask 类型并且运行background task.

usingWindows.ApplicationModel.Background;
usingWindows.UI.Notifications;
 
namespaceBackgroundStuff{
   publicsealedclassMyBackgroundTask:IBackgroundTask{
         
      publicvoidRun(IBackgroundTaskInstance taskInstance){
         SendToast("Hi this is background Task");
      }
                 
      publicstaticvoidSendToast(string message){
         vartemplate=ToastTemplateType.ToastText01;
         var xml =ToastNotificationManager.GetTemplateContent(template);
         var elements = xml.GetElementsByTagName("Text");
         var text = xml.CreateTextNode(message);
                          
         elements[0].AppendChild(text);
         var toast =newToastNotification(xml);
         ToastNotificationManager.CreateToastNotifier().Show(toast);
      }
   }
}

To make thisproject accessible in the UWPBackgroundDemo project, right click on References > Add References in Solution Explorer and add BackgroundStuff project.

让这个工程可以在UWPBackgroundDemo 使用,在资源管理器右击“引用”-->“添加引用”然后添加BackgroundStuff 工程。

 

Now, let us goto the Package.appxmanifest file of UWPBackgroundDemo project and add the followinginformation in Declarations tab.

现在打开UWPBackgroundDemo 工程的 Package.appxmanifest  文件,并在“声明”tab页添加下面信息。


·       First build the Background stuff project, then build andexecute the UWPBackgroundDemo project.

·       When the above code is compiled and executed, you will see thefollowing window.

首先编译 Background stuff 项目,然后编译执行UWPBackgroundDemo 项目。

编译执行通过,在弹出的窗口,点击“Button",后台任务将执行,并且在窗口的右下边显示提示信息。


发布了32 篇原创文章 · 获赞 7 · 访问量 4万+

猜你喜欢

转载自blog.csdn.net/mochounv/article/details/70163116
UWP