How to create and debug a background task in Windows 8 – Part 2

In the previous post we’ve created and configured a background task for our Windows 8 application: we’ve created a separate project for the task and we’ve configured the manifest file. Now it’s time to write the code in the client to register the background task, so that the application can take advantage of it. We’re going to register the background task we’ve created in the previous post: a timer based task that simply display a toast notification.

Here is the code that we insert in the MainPage.xaml.cs file, which is the code behind of the first page that is loaded when the application starts.

private async void RegisterBackgroundTask()
{
    try
    {
        BackgroundAccessStatus status = await BackgroundExecutionManager.RequestAccessAsync();
        if (status == BackgroundAccessStatus.AllowedWithAlwaysOnRealTimeConnectivity || status == BackgroundAccessStatus.AllowedMayUseActiveRealTimeConnectivity)
        {
            bool isRegistered = BackgroundTaskRegistration.AllTasks.Any(x => x.Value.Name == "Notification task");
            if (!isRegistered)
            {
                BackgroundTaskBuilder builder = new BackgroundTaskBuilder
                {
                    Name = "Notification task",
                    TaskEntryPoint =
                        "BackgroundTask.NotificationTask.NotificationTask"
                };
                builder.SetTrigger(new TimeTrigger(60, false));
                builder.AddCondition(new SystemCondition(SystemConditionType.InternetAvailable));
                BackgroundTaskRegistration task = builder.Register();
            }
        }
    }
    catch (Exception ex)
    {
        Debug.WriteLine("The access has already been granted");
    }
}

The first thing we do is ask the user the permission to run the background task by calling the metod RequestAccesAsync of the BackgroundExecutionManager class. When this method is called, a dialog box is displayed and the user can choose if the wants to enable or not the task: the choice is returned by the method embedded into a BackgroundAccessStatus enumerator. You will immediately notice that the whole code is embedded into a try / catch statement: this is required due to a bug in WinRT APIs, that returns an exception in case the user has already accepted to run the background task.

In case the user has confirmed to run the task we search if it’s already registered in the operating system. Unlike in Windows Phone, in fact, it’s possible to register the same task multiple times: in Windows Phone, instead,  you’ll get an exception. To accomplish this task we access to the collection of all the registered tasks (BackgroundTasksRegistration.AllTasks) and we look for a task which name is Notification task: later you’ll see that this is the name we set for our task.

If the task isn’t registered yet, we go on and register it: we create a new BackgroundTaskBuilder object and we set two properties: Name, which is the identifer of the task (it’s the one we’ve used before to check if it’s already registered or not), and TaskEntryPoint, which is the same value we set in the Entry point parameter of the manifest: it’s the full name of the class which hosts the background task, plus the namespace. In our example, the entry point is BackgroundTask.NotificationTask.NotificationTask.

It’s now time to define the type of background task we’re going to register: we do this by using the SetTrigger method on the BackgroundTaskBuilder object. Since in this example we’re going to create a timer task, we set a new TimeTrigger and we choose to run it every 60 minutes. Background tasks in Windows 8 support also conditions, which are a great way to make sure that a task is execute only when one or more criteria are satisfied: in this example, since we’re going to simulate a background task that periodically checks for some news, we add a SystemCondition of type InternetAvailable. This way, we can avoid to check in the background task if there is an active Internet connection because, if it’s not the case, the task won’t be executed at all.

In the end we register the task by calling the Register method. Last but not the least, we need to add a reference of the background task’s project to the client: let’s right click on the client project, choose Add reference and, by using the Solutions tab, double click on the background’s task project.

It’s time to debug!

We’ve created a background task but how can we debug it? Obviously, Visual Studio 2012 offers a smarter way than simply waiting for the condition to be satisfied (in our example, an Internet connection is available and the 60 minutes time trigger is reached). First we have to register the task when the application is launched: in this example we’re going to call the RegisteredBackgroundTask method we’ve just defined when the MainPage is initalized, so we call it in the constructor.

The first time the application is launched, you’ll see the dialog that will ask you the permission to run in background: confirm it and, once the application is started, go back in Visual Studio. Now right click with your mouse on one of the empty spaces near the toolbars and choose to display the Debug location toolbar. Near the name of the process you’ll find a dropdown menu, with some precious options that will allow you to simulate the various states of the application lifecycle (Suspend, Resume or Suspend and shutdown): in our case, since we’ve registered a background task, you will see another option with the name of our background task, that is Notification task.

Click on it and… voilà, your background task will be executed: if you set a breakpoint on the Run method of your background task’s project, you’ll see that is triggered and you’ll be able to debug it as you would normally do with another application.

And if it doesn’t work? Here are some common things to check in case you have problems:

  • Make sure that the background task’s project type is Windows Runtime Component.
  • The client should have a reference of the background’s task project: check the References tree of your client’s project.
  • Check the application’s settings (using the setting’s icon in the charm bar) and make sure that both notifications and background tasks are enabled.
  • Make sure that the entry point is correct,  both in the manifest and in the code. It should be the name of the class with, as prefix, the full namespace.

If you want to play with background tasks, here is the link to download the sample project used in this tutorial.

Download the source code

This entry was posted in Uncategorized. Bookmark the permalink.

20 Responses to How to create and debug a background task in Windows 8 – Part 2

  1. Tim says:

    Hi
    First I’d like to say thanks for a bunch great guides!
    I am currently trying to get a background task to update a database.
    I following your guide on SQLite, and managed to get it working while the app is in the foreground, but when I move everything over to a separate windows runtime component I get > 200 errors.
    for example;

    A public type has a namespace (‘Tasks’) that shares no common prefix with other namespaces (‘SQLite’). All types within a Windows Metadata file must exist in a sub namespace of the namespace that is implied by the file name.

    and

    ‘SQLite.SQLiteAsyncConnection.CreateTableAsync()’ is a generic method. Windows Runtime methods cannot be generic.

    Is it possible to get SQLite-net running in the background?
    if so would it be too much to ask to get a follow up post on setting it up?

    Thanks
    Tim

  2. Adam Walker says:

    Great article! Got one question… Is it possible to send any model data from the app to the background task? For example, if I had a username and a password stored in the app, could I somehow get it to the background task? Or is there someway of accessing a shared isolated storage between the client and the background task?

    Appreciate your help as I’m a little stumped on this one!

    • Hi Adam,
      like in Windows Phone the storage is shared between the app and the background task. If you write some stuff in the local storage of the application, then you’ll be able to read it in the background task using the same storage APIs.

      • Adam Walker says:

        Thanks! Literally figured that out as you replied. Turns out I just missed the .xml from my file name, so was getting the old file not found error. User error prevails as usual 😉

        Thanks for the quick response though!

  3. Rakesh says:

    thank you for your effort. I tried your sample, but my doubt is, i cannot see the the toast at all. The brake point is moving to notificationtask class, and each line of code is executing. Still the toast is invisible to me. Can you please tell me what magic is taking place there.

  4. Ramprasath says:

    Hi,
    Thanks a lot for the clear usage explanation. Just got a quick question, seems the minimum value for a TimeTrigger could be 15 minutes, is there a way to handle this with minimum values say 1 or 2 minutes ? Please let me know if i’m wrong any where.

    Thanks
    -Ram

  5. Matt Small says:

    Thanks for the great article on this! You correctly pointed out that the background task needs to be a Windows Runtime Component – and that was the problem in my code!

  6. Farhan says:

    Thanks for great article. I am using background task, but in task manager my app always remains in suspended when I click close it. It never gets killed. How can I overcome this situation ? Thanks

    • Hi, what do you exactly mean with “when I click close it?”. The app is killed by the operating system only when you’re running out of memory. If you want to test this scenario, you can use the options that are available in Visual Studio in the Debug Location panel (see the last screenshot of the post): by clicking on the Suspend and shutdown option, you can simulate that your application has been killed by the OS.

  7. Flavius Demian says:

    This is really really useful,,,not many devs use backgroundtasks and there isn’t that much documentation in this area. I am working on a chat application and I want to intercept with a background task the toast in order to redirect to a specific page and I really have to read a lot…Let me ask you ..this should be the way no? with a task of type Push Notification…

    • qmatteoq says:

      Yes, in this case instead of using background task you should use push notification: every time there’s a new message for the user, your server should send a push notification to the app, which will react accordingly. It’s a similar approach to the one made by Skype: when you get a message, you receive a toast notification and, tapping on it, you’re redirected to the conversation.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.