Windows 10 Development Tutorial (PDF

Add to My manuals
195 Pages

advertisement

Windows 10 Development Tutorial (PDF | Manualzz

The Universal Windows Platform (UWP) introduces new mechanisms, which allow the applications to perform some functionality while the application is not running in the foreground. UWP also increases the ability of the applications to extend their execution time in the background for Background Tasks and Triggers. Background execution is the real complementary tail to the application lifecycle.

Important features of Background Tasks are:

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

 When a background task is triggered, its associated handler runs and performs the work of the background task.

 A background task can run even when the app that registered the background task is suspended.

 They are part of the standard application platform and essentially provide an app with the ability to register for a system event (trigger). When that event occurs, they run a predefined block of code in the background. System triggers include events such as changes in network connectivity or the system time zone.

 Background Execution is not guaranteed, so it is not suitable for critical functions and features.

 The OS has a limitation as to how many background tasks can run at the same time. So even when trigger is fired and conditions are met, the task can still not run.

Create and Register Background Task

Create a background task class and register it to run when your app is not in the foreground. You can run code in the background by writing classes that implement the

IBackgroundTask interface. The following sample code shows a very basic starting point for a background task class. public sealed class MyBackgroundTask : IBackgroundTask

{

public void Run(IBackgroundTaskInstance taskInstance)

{

// write code

}

}

116

Windows 10 Apps Development

You can request access for background task as follows. var access = await BackgroundExecutionManager.RequestAccessAsync();

switch (access)

{

case BackgroundAccessStatus.Unspecified:

break;

case

BackgroundAccessStatus.AllowedMayUseActiveRealTimeConnectivity:

break;

case

BackgroundAccessStatus.AllowedWithAlwaysOnRealTimeConnectivity:

break;

case BackgroundAccessStatus.Denied:

break;

default:

break;

}

To build and register the background task, use the following code. var task = new BackgroundTaskBuilder

{

Name = "My Task",

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

}; var trigger = new ApplicationTrigger(); task.SetTrigger(trigger); task.Register(); await trigger.RequestAsync();

117

Windows 10 Apps Development

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

1. Create a new blank UWP project

UWPBackgroundDemo’

and add one button in the XAML file.

<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">

<Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">

<Button x:Name="button" Content="Button" HorizontalAlignment="Left"

Margin="159,288,0,0" VerticalAlignment="Top" Click="button_Click"/>

</Grid>

</Page>

2. Given below is the button click event implementation in which the background task is registered. using System; using Windows.ApplicationModel.Background; using Windows.UI.Xaml; using Windows.UI.Xaml.Controls;

// The Blank Page item template is http://go.microsoft.com/fwlink/?LinkId=402352&clcid=0x409 documented at namespace UWPBackgroundDemo

{

/// <summary>

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

/// </summary>

public sealed partial class MainPage : Page

{

118

Windows 10 Apps Development

public MainPage()

{

this.InitializeComponent();

}

private async void button_Click(object sender, RoutedEventArgs e)

{

var access = await BackgroundExecutionManager.RequestAccessAsync();

switch (access)

{

case BackgroundAccessStatus.Unspecified:

break;

case

BackgroundAccessStatus.AllowedMayUseActiveRealTimeConnectivity:

break;

case

BackgroundAccessStatus.AllowedWithAlwaysOnRealTimeConnectivity:

break;

case BackgroundAccessStatus.Denied:

break;

default:

break;

}

var task = new BackgroundTaskBuilder

{

Name = "My Task",

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

};

var trigger = new ApplicationTrigger();

task.SetTrigger(trigger);

var condition = new

SystemCondition(SystemConditionType.InternetAvailable);

task.Register();

119

Windows 10 Apps Development

await trigger.RequestAsync();

}

}

}

}

3. Now create another project, but this time select Windows Runtime Component

(Universal Windows) from the menu and give the name Background stuff to this project.

4. Given below is the C# code. which contains MyBackgroundTask class implantation and it will run the background task. using Windows.ApplicationModel.Background; using Windows.UI.Notifications; namespace BackgroundStuff

{

public sealed class MyBackgroundTask : IBackgroundTask

{

public void Run(IBackgroundTaskInstance taskInstance)

{

120

Windows 10 Apps Development

SendToast("Hi this is background Task");

}

public static void SendToast(string message)

{

var template = ToastTemplateType.ToastText01;

var xml = ToastNotificationManager.GetTemplateContent(template);

var elements = xml.GetElementsByTagName("Test");

var text = xml.CreateTextNode(message);

elements[0].AppendChild(text);

var toast = new ToastNotification(xml);

ToastNotificationManager.CreateToastNotifier().Show(toast);

}

}

}

5. To make this project accessible in the UWPBackgroundDemo project, right click on

References > Add References in Solution Explorer and add BackgroundStuff project.

6. Now, let us go to the Package.appxmanifest file of

UWPBackgroundDemo

project and add the following information in Declarations tab.

121

Windows 10 Apps Development

7. First build the Background stuff project, then build and execute the

UWPBackgroundDemo project.

8. When the above code is compiled and executed, you will see the following window.

9. When you click the button, it will run the background task and will show a notification at the right end of your window.

122

advertisement

Related manuals

advertisement

Table of contents