Introduction
In this article I will talk about how to plan your background app(Design) in Windows 8.1, then to create a background app(Develop) using Visual Studio 2013 and then to troubleshoot(Debug).
This article is based on C# and a full working sample code is posted with this article.
Design
1. Don't do heavy weight lifting in the background
There are CPU and Network quotas for background apps to keep the device running smoothly as well to avoid network overages.
CPU:
Network:
More info - http://msdn.microsoft.com/en-us/library/windows/apps/hh977056.aspx
2. Handle Cancel and Resume
Your task may be cancelled by the Operating System if it is going over the quota, so you will have to design your app to handle the cancel operation.
More info - http://msdn.microsoft.com/en-us/library/windows/apps/hh977052.aspx
3. Lock screen capable or not
If your app needs to show some real time data then most probably it is a lock screen capable app. In case of lock screen capable you have the following triggers to start your task.
If the app doesn't need to be on lock screen then here is the other set of triggers to use
Triggering the back ground task is handled by the Operating System and so no need to plan for your own timer code.
If your task has some dependency on the machine state then you can add the following conditions to your trigger so that the task will wait until the condition is met.
Develop
1. Create a Windows Store app using Visual Studio 2013
I'm assuming the audience are capable of creating a simple Windows store app. If you are new to Windows store app please refer the following document.
http://msdn.microsoft.com/en-us/library/windows/apps/br211384.aspx
2. Add a new project to the Store app you created in step 1
2.1 Create a new project for background tasks and add it to your solution. To do this, right-click on your solution and select Add->New Project. Then select the Windows Runtime Component project type, name the project, and click OK.
2.2 Create a new class that implements the IBackgroundTask interface. The Run method is a required entry point that will be called when the specified event is triggered; this method is required in every background task.
public sealed class CPBackgroundTask : IBackgroundTask
{
public void Run(IBackgroundTaskInstance taskInstance)
{
try
{
BackgroundTaskDeferral _deferral = taskInstance.GetDeferral();
System.Diagnostics.Debug.WriteLine("Starting backgroundtask");
System.Diagnostics.Debug.WriteLine("Stop backgroundtask");
_deferral.Complete();
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine("exception backgroundtask");
}
}
}
The above sample code gets the deferral, saves it, and releases it when the asynchronous code is complete.
In my attached sample code toast message notification is shown when the background task is run.
3. Add a button to register the background task in MainPage.xaml.cs
private async void Button_Click_Register(object sender, RoutedEventArgs e)
{
try
{
var builder = new BackgroundTaskBuilder();
builder.Name = exampleTaskName;
builder.TaskEntryPoint = "CPBackgroundTasks.CPBackgroundTask";
builder.SetTrigger(new SystemTrigger(SystemTriggerType.TimeZoneChange, false));
builder.AddCondition(new SystemCondition(SystemConditionType.UserPresent));
BackgroundTaskRegistration task = builder.Register();
}
catch(Exception ex)
{
System.Diagnostics.Debug.WriteLine(ex.Message);
}
}
3.1 If you want place your app in the lock screen enable the following code. But the attached sample is not a lock screen capable app
BackgroundAccessStatus baStatus = await BackgroundExecutionManager.RequestAccessAsync();
3.1.1 Also set the manifest options in Package.appxmanifest
3.2 Set the background task entry point
3.2.1 Below line set the entry point for this background task.
builder.TaskEntryPoint = "CPBackgroundTasks.CPBackgroundTask";
3.2.2 Update the Package.appxmanifest file as below.
<Extension Category="windows.backgroundTasks" EntryPoint="CPBackgroundTasks.CPBackgroundTask">
<BackgroundTasks>
<Task Type="systemEvent" />
</BackgroundTasks>
</Extension>
3.3 below line sets a trigger when the TimeZone is changed in the system and then a additional condition is added to make sure the user is present at the time execution.
builder.SetTrigger(new SystemTrigger(SystemTriggerType.TimeZoneChange, false));
builder.AddCondition(new SystemCondition(SystemConditionType.UserPresent));
3.4 Final step is to register the background task using the following
BackgroundTaskRegistration task = builder.Register();
Debug
Since the background task are based on system events and/or timer we need a way to trigger the background task for debugging purpose. Visual Studio 2013 has a wonderful feature to execute the background task at any time.
1. Set a breakpoint in the Run method in CPBackgroundTasks.cs .
2. Run the app using F5 from Visual Studio, then click Register Backgound task button in the app.
3. Then go to Visual Studio window as shown below to activate the background task.
This will take you to the break point inside Run method, now you are ready to debug your code.
More info: http://msdn.microsoft.com/en-us/library/windows/apps/jj542416.aspx
Conclusion
As you can see above creating a Windows 8.1 background process is a piece of cake, but should be used cautiously as it may degrade the Operating System performance.