You are on page 1of 14

//*********************************************************

//
// Copyright (c) Microsoft. All rights reserved.
// This code is licensed under the MIT License (MIT).
// THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
// ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
// IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
// PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
//
//*********************************************************

using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Windows.Foundation.Collections;
using Windows.UI.Xaml.Controls;
using Windows.ApplicationModel.Activation;
using Windows.ApplicationModel.Background;
using Windows.Storage;
using Windows.UI.Xaml;

namespace SDKTemplate
{
public partial class MainPage : Page
{
public const string FEATURE_NAME = "Background Activation";

List<Scenario> scenarios = new List<Scenario>


{
new Scenario() { Title="Background Task",
ClassType=typeof(SampleBackgroundTask)},
new Scenario() { Title="Background Task with Condition",
ClassType=typeof(SampleBackgroundTaskWithCondition)},
new Scenario() { Title="Servicing Complete Task",
ClassType=typeof(ServicingCompleteTask)},
new Scenario() { Title="Background Task with Time Trigger",
ClassType=typeof(TimeTriggeredTask) },
new Scenario() { Title="Background Task with Application Trigger",
ClassType=typeof(ApplicationTriggerTask) },
new Scenario() { Title="Grouped Background Task",
ClassType=typeof(GroupedBackgroundTask) },
};
}

public class Scenario


{
public string Title { get; set; }
public Type ClassType { get; set; }
}
}

namespace SDKTemplate
{
class BackgroundTaskSample
{
public const string SampleBackgroundTaskName = "SampleBackgroundTask";
public static string SampleBackgroundTaskProgress = "";
public static bool SampleBackgroundTaskRegistered = false;
public const string SampleBackgroundTaskWithConditionName =
"SampleBackgroundTaskWithCondition";
public static string SampleBackgroundTaskWithConditionProgress = "";
public static bool SampleBackgroundTaskWithConditionRegistered = false;

public const string ServicingCompleteTaskName = "ServicingCompleteTask";


public static string ServicingCompleteTaskProgress = "";
public static bool ServicingCompleteTaskRegistered = false;

public const string TimeTriggeredTaskName = "TimeTriggeredTask";


public static string TimeTriggeredTaskProgress = "";
public static bool TimeTriggeredTaskRegistered = false;

public const string ApplicationTriggerTaskName = "ApplicationTriggerTask";


public static string ApplicationTriggerTaskProgress = "";
public static string ApplicationTriggerTaskResult = "";
public static bool ApplicationTriggerTaskRegistered = false;

public const string GroupedBackgroundTaskName = "GroupedBackgroundTask";


public const string BackgroundTaskGroupId = "3F2504E0-5F89-41D3-9A0C-
0405E82C3333";
public const string BackgroundTaskGroupFriendlyName = "Background Task
Group";
public static string GroupedBackgroundTaskProgress = "";
public static bool GroupedBackgroundTaskRegistered = false;

// These strings are manipulated by multiple threads, so we must


// use a thread-safe container.
public static PropertySet TaskStatuses = new PropertySet();

/// <summary>
/// Register a background task with the specified taskEntryPoint, name,
trigger,
/// and condition (optional).
/// </summary>
/// <param name="taskEntryPoint">Task entry point for the background
task.</param>
/// <param name="name">A name for the background task.</param>
/// <param name="trigger">The trigger for the background task.</param>
/// <param name="condition">An optional conditional event that must be true
for the task to fire.</param>
public static BackgroundTaskRegistration RegisterBackgroundTask(String
taskEntryPoint, String name, IBackgroundTrigger trigger, IBackgroundCondition
condition, BackgroundTaskRegistrationGroup group = null)
{
if (TaskRequiresBackgroundAccess(name))
{
// If the user denies access, the task will not run.
var requestTask = BackgroundExecutionManager.RequestAccessAsync();
}

var builder = new BackgroundTaskBuilder();

builder.Name = name;

if (taskEntryPoint != null)
{
// If you leave the TaskEntryPoint at its default value, then the
task runs
// inside the main process from OnBackgroundActivated rather than
as a separate process.
builder.TaskEntryPoint = taskEntryPoint;
}

builder.SetTrigger(trigger);

if (condition != null)
{
builder.AddCondition(condition);

//
// If the condition changes while the background task is executing
then it will
// be canceled.
//
builder.CancelOnConditionLoss = true;
}

if (group != null)
{
builder.TaskGroup = group;
}

BackgroundTaskRegistration task = builder.Register();

UpdateBackgroundTaskRegistrationStatus(name, true);

//
// Remove previous completion status.
//
TaskStatuses.Remove(name);

return task;
}

/// <summary>
/// Unregister background tasks with specified name.
/// </summary>
/// <param name="name">Name of the background task to unregister.</param>
public static void UnregisterBackgroundTasks(String name,
BackgroundTaskRegistrationGroup group = null)
{
//
// If the given task group is registered then loop through all
background tasks associated with it
// and unregister any with the given name.
//
if (group != null)
{
foreach (var cur in group.AllTasks)
{
if (cur.Value.Name == name)
{
cur.Value.Unregister(true);
}
}
}
else
{
//
// Loop through all ungrouped background tasks and unregister any
with the given name.
//
foreach (var cur in BackgroundTaskRegistration.AllTasks)
{
if (cur.Value.Name == name)
{
cur.Value.Unregister(true);
}
}
}

UpdateBackgroundTaskRegistrationStatus(name, false);
}

/// <summary>
/// Retrieve a registered background task group. If no group is registered
with the given id,
/// then create a new one and return it.
/// </summary>
/// <returns>The task group associated with the given id</returns>
public static BackgroundTaskRegistrationGroup GetTaskGroup(string id,
string groupName)
{
var group = BackgroundTaskRegistration.GetTaskGroup(id);

if (group == null)
{
group = new BackgroundTaskRegistrationGroup(id, groupName);
}

return group;
}

/// <summary>
/// Store the registration status of a background task with a given name.
/// </summary>
/// <param name="name">Name of background task to store registration status
for.</param>
/// <param name="registered">TRUE if registered, FALSE if
unregistered.</param>
public static void UpdateBackgroundTaskRegistrationStatus(String name, bool
registered)
{
switch (name)
{
case SampleBackgroundTaskName:
SampleBackgroundTaskRegistered = registered;
break;
case SampleBackgroundTaskWithConditionName:
SampleBackgroundTaskWithConditionRegistered = registered;
break;
case ServicingCompleteTaskName:
ServicingCompleteTaskRegistered = registered;
break;
case TimeTriggeredTaskName:
TimeTriggeredTaskRegistered = registered;
break;
case ApplicationTriggerTaskName:
ApplicationTriggerTaskRegistered = registered;
break;
case GroupedBackgroundTaskName:
GroupedBackgroundTaskRegistered = registered;
break;
}
}

/// <summary>
/// Get the registration / completion status of the background task with
/// given name.
/// </summary>
/// <param name="name">Name of background task to retreive registration
status.</param>
public static String GetBackgroundTaskStatus(String name)
{
var registered = false;
switch (name)
{
case SampleBackgroundTaskName:
registered = SampleBackgroundTaskRegistered;
break;
case SampleBackgroundTaskWithConditionName:
registered = SampleBackgroundTaskWithConditionRegistered;
break;
case ServicingCompleteTaskName:
registered = ServicingCompleteTaskRegistered;
break;
case TimeTriggeredTaskName:
registered = TimeTriggeredTaskRegistered;
break;
case ApplicationTriggerTaskName:
registered = ApplicationTriggerTaskRegistered;
break;
case GroupedBackgroundTaskName:
registered = GroupedBackgroundTaskRegistered;
break;
}

var status = registered ? "Registered" : "Unregistered";

object taskStatus;
if (TaskStatuses.TryGetValue(name, out taskStatus))
{
status += " - " + taskStatus.ToString();
}

return status;
}

/// <summary>
/// Determine if task with given name requires background access.
/// </summary>
/// <param name="name">Name of background task to query background access
requirement.</param>
public static bool TaskRequiresBackgroundAccess(String name)
{
if ((name == TimeTriggeredTaskName) ||
(name == ApplicationTriggerTaskName))
{
return true;
}
else
{
return false;
}
}
}
}

namespace SDKTemplate
{
sealed partial class App : Application
{
/// <summary>
/// Override the Application.OnBackgroundActivated method to handle
background activation in
/// the main process. This entry point is used when
BackgroundTaskBuilder.TaskEntryPoint is
/// not set during background task registration.
/// </summary>
/// <param name="args"></param>
protected override void OnBackgroundActivated(BackgroundActivatedEventArgs
args)
{
BackgroundActivity.Start(args.TaskInstance);
}

/// <summary>
/// Register for grouped background task events in the Application
constructor.
/// </summary>
partial void Construct()
{
var group =
BackgroundTaskSample.GetTaskGroup(BackgroundTaskSample.BackgroundTaskGroupId,
BackgroundTaskSample.BackgroundTaskGroupFriendlyName);
group.BackgroundActivated += BackgroundActivity.Start;
}
}
}
//*********************************************************
//
// Copyright (c) Microsoft. All rights reserved.
// This code is licensed under the MIT License (MIT).
// THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
// ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
// IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
// PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
//
//*********************************************************

using System;
using SDKTemplate;
using Windows.ApplicationModel.Background;
using Windows.Storage;
using Windows.UI.Core;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Navigation;

// The Blank Page item template is documented at http://go.microsoft.com/fwlink/?


LinkId=234238

namespace SDKTemplate
{
/// <summary>
/// An empty page that can be used on its own or navigated to within a Frame.
/// </summary>
public sealed partial class ServicingCompleteTask : Page
{
// A pointer back to the main page. This is needed if you want to call
methods in MainPage such
// as NotifyUser()
MainPage rootPage = MainPage.Current;

public ServicingCompleteTask()
{
this.InitializeComponent();
}

/// <summary>
/// Invoked when this page is about to be displayed in a Frame.
/// </summary>
/// <param name="e">Event data that describes how this page was reached.
The Parameter
/// property is typically used to configure the page.</param>
protected override void OnNavigatedTo(NavigationEventArgs e)
{
foreach (var task in BackgroundTaskRegistration.AllTasks)
{
if (task.Value.Name ==
BackgroundTaskSample.ServicingCompleteTaskName)
{
AttachProgressAndCompletedHandlers(task.Value);

BackgroundTaskSample.UpdateBackgroundTaskRegistrationStatus(BackgroundTaskSample.Se
rvicingCompleteTaskName, true);
break;
}
}

UpdateUI();
}

/// <summary>
/// Register a ServicingCompleteTask.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void RegisterBackgroundTask(object sender, RoutedEventArgs e)
{
var task = BackgroundTaskSample.RegisterBackgroundTask(null,
BackgroundTaskSample.ServicingCompleteTaskName,
new
SystemTrigger(SystemTriggerType.ServicingComplete, false),
null);
AttachProgressAndCompletedHandlers(task);
UpdateUI();
}

/// <summary>
/// Unregister a ServicingCompleteTask.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void UnregisterBackgroundTask(object sender, RoutedEventArgs e)
{

BackgroundTaskSample.UnregisterBackgroundTasks(BackgroundTaskSample.ServicingComple
teTaskName);
UpdateUI();
}

/// <summary>
/// Attach progress and completed handers to a background task.
/// </summary>
/// <param name="task">The task to attach progress and completed handlers
to.</param>
private void AttachProgressAndCompletedHandlers(IBackgroundTaskRegistration
task)
{
task.Progress += new BackgroundTaskProgressEventHandler(OnProgress);
task.Completed += new BackgroundTaskCompletedEventHandler(OnCompleted);
}

/// <summary>
/// Handle background task progress.
/// </summary>
/// <param name="task">The task that is reporting progress.</param>
/// <param name="e">Arguments of the progress report.</param>
private void OnProgress(IBackgroundTaskRegistration task,
BackgroundTaskProgressEventArgs args)
{
var ignored = Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
{
var progress = "Progress: " + args.Progress + "%";
BackgroundTaskSample.ServicingCompleteTaskProgress = progress;
UpdateUI();
});
}

/// <summary>
/// Handle background task completion.
/// </summary>
/// <param name="task">The task that is reporting completion.</param>
/// <param name="e">Arguments of the completion report.</param>
private void OnCompleted(IBackgroundTaskRegistration task,
BackgroundTaskCompletedEventArgs args)
{
UpdateUI();
}
/// <summary>
/// Update the scenario UI.
/// </summary>
private async void UpdateUI()
{
await Dispatcher.RunAsync(CoreDispatcherPriority.Normal,
() =>
{
RegisterButton.IsEnabled = !
BackgroundTaskSample.ServicingCompleteTaskRegistered;
UnregisterButton.IsEnabled =
BackgroundTaskSample.ServicingCompleteTaskRegistered;
Progress.Text = BackgroundTaskSample.ServicingCompleteTaskProgress;
Status.Text =
BackgroundTaskSample.GetBackgroundTaskStatus(BackgroundTaskSample.ServicingComplete
TaskName);
});
}

}
}
//*********************************************************
//
// Copyright (c) Microsoft. All rights reserved.
// This code is licensed under the MIT License (MIT).
// THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
// ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
// IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
// PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
//
//*********************************************************

using System;
using Windows.ApplicationModel.Background;
using Windows.Storage;
using Windows.UI.Core;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Navigation;
using SDKTemplate;

// The Blank Page item template is documented at http://go.microsoft.com/fwlink/?


LinkId=234238

namespace SDKTemplate
{
/// <summary>
/// An empty page that can be used on its own or navigated to within a Frame.
/// </summary>
public sealed partial class SampleBackgroundTask : Page
{
// A pointer back to the main page. This is needed if you want to call
methods in MainPage such
// as NotifyUser()
private MainPage rootPage = MainPage.Current;

public SampleBackgroundTask()
{
this.InitializeComponent();
}

/// <summary>
/// Invoked when this page is about to be displayed in a Frame.
/// </summary>
/// <param name="e">Event data that describes how this page was reached.
The Parameter
/// property is typically used to configure the page.</param>
protected override void OnNavigatedTo(NavigationEventArgs e)
{
foreach (var task in BackgroundTaskRegistration.AllTasks)
{
if (task.Value.Name ==
BackgroundTaskSample.SampleBackgroundTaskName)
{
AttachProgressAndCompletedHandlers(task.Value);

BackgroundTaskSample.UpdateBackgroundTaskRegistrationStatus(BackgroundTaskSample.Sa
mpleBackgroundTaskName, true);
break;
}
}

UpdateUI();
}

/// <summary>
/// Register a SampleBackgroundTask.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void RegisterBackgroundTask(object sender, RoutedEventArgs e)
{
var task = BackgroundTaskSample.RegisterBackgroundTask(null,

BackgroundTaskSample.SampleBackgroundTaskName,
new
SystemTrigger(SystemTriggerType.TimeZoneChange, false),
null);
AttachProgressAndCompletedHandlers(task);
UpdateUI();
}

/// <summary>
/// Unregister a SampleBackgroundTask.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void UnregisterBackgroundTask(object sender, RoutedEventArgs e)
{

BackgroundTaskSample.UnregisterBackgroundTasks(BackgroundTaskSample.SampleBackgroun
dTaskName);
UpdateUI();
}

/// <summary>
/// Attach progress and completed handers to a background task.
/// </summary>
/// <param name="task">The task to attach progress and completed handlers
to.</param>
private void AttachProgressAndCompletedHandlers(IBackgroundTaskRegistration
task)
{
task.Progress += new BackgroundTaskProgressEventHandler(OnProgress);
task.Completed += new BackgroundTaskCompletedEventHandler(OnCompleted);
}

/// <summary>
/// Handle background task progress.
/// </summary>
/// <param name="task">The task that is reporting progress.</param>
/// <param name="e">Arguments of the progress report.</param>
private void OnProgress(IBackgroundTaskRegistration task,
BackgroundTaskProgressEventArgs args)
{
var ignored = Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
{
var progress = "Progress: " + args.Progress + "%";
BackgroundTaskSample.SampleBackgroundTaskProgress = progress;
UpdateUI();
});
}

/// <summary>
/// Handle background task completion.
/// </summary>
/// <param name="task">The task that is reporting completion.</param>
/// <param name="e">Arguments of the completion report.</param>
private void OnCompleted(IBackgroundTaskRegistration task,
BackgroundTaskCompletedEventArgs args)
{
UpdateUI();
}

/// <summary>
/// Update the scenario UI.
/// </summary>
private async void UpdateUI()
{
await Dispatcher.RunAsync(CoreDispatcherPriority.Normal,
() =>
{
RegisterButton.IsEnabled = !
BackgroundTaskSample.SampleBackgroundTaskRegistered;
UnregisterButton.IsEnabled =
BackgroundTaskSample.SampleBackgroundTaskRegistered;
Progress.Text = BackgroundTaskSample.SampleBackgroundTaskProgress;
Status.Text =
BackgroundTaskSample.GetBackgroundTaskStatus(BackgroundTaskSample.SampleBackgroundT
askName);
});
}
}
}
//*********************************************************
//
// Copyright (c) Microsoft. All rights reserved.
// This code is licensed under the MIT License (MIT).
// THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
// ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
// IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
// PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
//
//*********************************************************

using System;
using SDKTemplate;
using Windows.ApplicationModel.Background;
using Windows.Storage;
using Windows.UI.Core;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Navigation;

// The Blank Page item template is documented at http://go.microsoft.com/fwlink/?


LinkId=234238

namespace SDKTemplate
{
/// <summary>
/// An empty page that can be used on its own or navigated to within a Frame.
/// </summary>
public sealed partial class SampleBackgroundTaskWithCondition : Page
{
// A pointer back to the main page. This is needed if you want to call
methods in MainPage such
// as NotifyUser()
MainPage rootPage = MainPage.Current;

public SampleBackgroundTaskWithCondition()
{
this.InitializeComponent();
}

/// <summary>
/// Invoked when this page is about to be displayed in a Frame.
/// </summary>
/// <param name="e">Event data that describes how this page was reached.
The Parameter
/// property is typically used to configure the page.</param>
protected override void OnNavigatedTo(NavigationEventArgs e)
{
foreach (var task in BackgroundTaskRegistration.AllTasks)
{
if (task.Value.Name ==
BackgroundTaskSample.SampleBackgroundTaskWithConditionName)
{
AttachProgressAndCompletedHandlers(task.Value);

BackgroundTaskSample.UpdateBackgroundTaskRegistrationStatus(BackgroundTaskSample.Sa
mpleBackgroundTaskWithConditionName, true);
break;
}
}
UpdateUI();
}

/// <summary>
/// Register a SampleBackgroundTaskWithCondition.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void RegisterBackgroundTask(object sender, RoutedEventArgs e)
{
var task = BackgroundTaskSample.RegisterBackgroundTask(null,

BackgroundTaskSample.SampleBackgroundTaskWithConditionName,
new
SystemTrigger(SystemTriggerType.TimeZoneChange, false),
new
SystemCondition(SystemConditionType.InternetAvailable));
AttachProgressAndCompletedHandlers(task);
UpdateUI();
}

/// <summary>
/// Unregister a SampleBackgroundTaskWithCondition.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void UnregisterBackgroundTask(object sender, RoutedEventArgs e)
{

BackgroundTaskSample.UnregisterBackgroundTasks(BackgroundTaskSample.SampleBackgroun
dTaskWithConditionName);
UpdateUI();
}

/// <summary>
/// Attach progress and completed handers to a background task.
/// </summary>
/// <param name="task">The task to attach progress and completed handlers
to.</param>
private void AttachProgressAndCompletedHandlers(IBackgroundTaskRegistration
task)
{
task.Progress += new BackgroundTaskProgressEventHandler(OnProgress);
task.Completed += new BackgroundTaskCompletedEventHandler(OnCompleted);
}

/// <summary>
/// Handle background task progress.
/// </summary>
/// <param name="task">The task that is reporting progress.</param>
/// <param name="e">Arguments of the progress report.</param>
private void OnProgress(IBackgroundTaskRegistration task,
BackgroundTaskProgressEventArgs args)
{
var ignored = Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
{
var progress = "Progress: " + args.Progress + "%";
BackgroundTaskSample.SampleBackgroundTaskWithConditionProgress =
progress;
UpdateUI();
});
}

/// <summary>
/// Handle background task completion.
/// </summary>
/// <param name="task">The task that is reporting completion.</param>
/// <param name="e">Arguments of the completion report.</param>
private void OnCompleted(IBackgroundTaskRegistration task,
BackgroundTaskCompletedEventArgs args)
{
UpdateUI();
}

/// <summary>
/// Update the scenario UI.
/// </summary>
private async void UpdateUI()
{
await Dispatcher.RunAsync(CoreDispatcherPriority.Normal,
() =>
{
RegisterButton.IsEnabled = !
BackgroundTaskSample.SampleBackgroundTaskWithConditionRegistered;
UnregisterButton.IsEnabled =
BackgroundTaskSample.SampleBackgroundTaskWithConditionRegistered;
Progress.Text =
BackgroundTaskSample.SampleBackgroundTaskWithConditionProgress;
Status.Text =
BackgroundTaskSample.GetBackgroundTaskStatus(BackgroundTaskSample.SampleBackgroundT
askWithConditionName);
});
}
}
}

You might also like