Français English

Windows Phone 8.1 Update Task

Tags: .NET 4.5, Windows Phone 8.1, WP8.1, wp_dev, BackgroudTask

 

Amongst the new features of Windows Phone 8.1 (Silverlight), there is a new background task : the Update Task.

As the name suggest, it is a background task that is run when the application is updated.

If you need to update some data, settings, etc… when you update your app, this is for you.

 

Implementing the Update Task

I will show an example of an update task sending a toast notification when the application is updated.

Adding a WinRT component

The task class must reside in a WinRT component, so add one to the solution

Create a background task class

Now add a class. A background task class must sealed, implement the IBackgroundTask interface. The interface has only one method (Run) to implement. This is the method the OS call when it wants to start the background task.

So that is where I’ll put my code sending a toast, as showed here :

public sealed class MyUpdateTask : IBackgroundTask
{
    public void Run(IBackgroundTaskInstance taskInstance)
    {
        var toastnotifier = ToastNotificationManager.CreateToastNotifier();

        var toastDescriptor = ToastNotificationManager.GetTemplateContent(ToastTemplateType.ToastText02);

        var txtNodes = toastDescriptor.GetElementsByTagName("text");

        txtNodes[0].AppendChild(toastDescriptor.CreateTextNode("UpdateTask"));
        txtNodes[1].AppendChild(toastDescriptor.CreateTextNode(string.Format("Update time : {0}", DateTime.Now)));

        var toast = new ToastNotification(toastDescriptor);

        toastnotifier.Show(toast);
    }
}

That’s all we need to do for the class itself !

Add the background task to the application

First, add a reference to the background task component in the project

Add the Update Task capability to your application in the Package.appxmanifest :

In the same screen, enter the full class name (including namespace) of your background task

In this exemple, we need also to add toast capability

Note that, contrary to “normal” background task, we don’t need to register the task at first start.

Test

To test, just run your application from Visual Studio.

Stop, and change the version number in the Package.appxmanifest

Run again, and you should see

Note that if you modify the Update Task, it is that version that will be run, and not the one that was installed with the previous version of the application (hopefully, if you want to upgrade app data to the latest version, for instance)

 

The sample source is here

Comments powered by Disqus