Click here to Skip to main content
16,016,744 members
Articles / Desktop Programming / XAML
Tip/Trick

3-D's of Windows 8.1 Store Background App

Rate me:
Please Sign up or sign in to vote.
4.86/5 (4 votes)
11 Mar 2014CPOL3 min read 10.8K   6   1
Writing a Windows store background app from the scratch

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:

Image 1

Network:

Image 2

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.

Image 3

If the app doesn't need to be on lock screen then here is the other set of triggers to use

Image 4

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.

Image 5

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.

C#
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

C#
private async void Button_Click_Register(object sender, RoutedEventArgs e)
{
   try
   {
 //use this if you want to place your app in the lock screen and need to modify the manifest
        //BackgroundAccessStatus baStatus = await BackgroundExecutionManager.RequestAccessAsync();
        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

C#
BackgroundAccessStatus baStatus = await BackgroundExecutionManager.RequestAccessAsync(); 

3.1.1 Also set the manifest options in Package.appxmanifest

Image 6

3.2 Set the background task entry point

3.2.1 Below line set the entry point for this background task.

C#
builder.TaskEntryPoint = "CPBackgroundTasks.CPBackgroundTask";

3.2.2 Update the Package.appxmanifest file as below.

XML
<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.

C#
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

C#
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.

Image 7

3. Then go to Visual Studio window as shown below to activate the background task.

Image 8

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.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer
United States United States
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
GeneralMy vote of 5 Pin
Jim Meadors11-Mar-14 19:21
Jim Meadors11-Mar-14 19:21 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.