Updating Metro tiles in the background periodically

April 20, 2012 at 9:00 am | Posted in HTML/JavaScript, Metro, Windows 8 | 3 Comments

This is an example of how to use a background task to update an app’s tiles.

First, here is a default html file with a button and status line.

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>HelpTileUpdate</title>

    <!-- WinJS references -->
    <link href="//Microsoft.WinJS.0.6/css/ui-dark.css" rel="stylesheet">
    <script src="//Microsoft.WinJS.0.6/js/base.js"></script>
    <script src="//Microsoft.WinJS.0.6/js/ui.js"></script>

    <!-- HelpTileUpdate references -->
    <link href="/css/default.css" rel="stylesheet">
    <script src="/js/default.js"></script>
</head>
<body>
    <button id="startService">Start Background</button>
    <div id="status">Status of service</div>
</body>
</html>

Next, the default.js which handles the button click event.   This handler requests to use the lock screen (required for timer background tasks) and then registers the task with a timeTrigger set for 15 minutes (the minimum allowed interval).

// For an introduction to the Blank template, see the following documentation:
// http://go.microsoft.com/fwlink/?LinkId=232509
(function () {
    "use strict";

    var app = WinJS.Application;

    app.onactivated = function (eventObject) {
        if (eventObject.detail.kind === Windows.ApplicationModel.Activation.ActivationKind.launch) {
            if (eventObject.detail.previousExecutionState !== Windows.ApplicationModel.Activation.ApplicationExecutionState.terminated) {
                // TODO: This application has been newly launched. Initialize
                // your application here.
            } else {
                // TODO: This application has been reactivated from suspension.
                // Restore application state here.
            }
            WinJS.UI.processAll().then(function onComplete(processedElements) {
                document.getElementById("startService").addEventListener("click", beginBackgroundService, false);
        });
        }
    };

    app.oncheckpoint = function (eventObject) {
        // TODO: This application is about to be suspended. Save any state
        // that needs to persist across suspensions here. You might use the
        // WinJS.Application.sessionState object, which is automatically
        // saved and restored across suspension. If you need to complete an
        // asynchronous operation before your application is suspended, call
        // eventObject.setPromise().
    };

    app.start();

    function beginBackgroundService() {

        requestLockScreenAccess();
        registerBackgroundTask();
    }

    function displayStatus(msg) {
        document.getElementById("status").innerText = msg;
    }

    function registerBackgroundTask() {
        var builder = new Windows.ApplicationModel.Background.BackgroundTaskBuilder();
        builder.name = "myTask";
        builder.taskEntryPoint = "backgroundtask.js";
        var timeTrigger = new Windows.ApplicationModel.Background.TimeTrigger(15, false);
        //var timeTrigger = new Windows.ApplicationModel.Background.SystemTrigger(Windows.ApplicationModel.Background.SystemTriggerType.timeZoneChange, false);
        builder.setTrigger(timeTrigger);
        var conditionType = Windows.ApplicationModel.Background.SystemConditionType.internetAvailable;
        var taskCondition = new Windows.ApplicationModel.Background.SystemCondition(conditionType);
        builder.addCondition(taskCondition);
        var backgroundTaskRegistration = builder.register();

    }

    //
    // This is a helper function to add your app to the lock screen.
    // Time events require the app to be on the lock screen to fire
    //
    function requestLockScreenAccess() {
        var Background = Windows.ApplicationModel.Background;

        //
        // An app can call the add or query API as many times as it wants; however, it will only present the dialog box to the user one time.
        //
        Background.BackgroundExecutionManager.requestAccessAsync().then(function (result) {
            switch (result) {
                case Background.BackgroundAccessStatus.denied:
                    displayStatus("This app is not on the lock screen.");
                    break;

                case Background.BackgroundAccessStatus.allowedWithRealTimeConnectivity:
                    displayStatus("This app is on the lock screen and has access to Real Time Connectivity.");
                    break;

                case Background.BackgroundAccessStatus.allowedWithoutRealTimeConnectivity:
                    displayStatus("This app is on the lock screen, but does not have access to Real Time Connectivity.");
                    break;

                case Background.BackgroundAccessStatus.unspecified:
                    displayStatus("The user has not yet taken any action. This is the default setting and the app is not on the lock screen.");
                    break;
            }
        }, function (e) {
            displayStatus(e);
            console.log(e);
        });
    }
})();

Next, you will need to add a backgroundtask.js file to your project. This code simply checks the date and writes it to a wide tile.

//Background task
//Checks for new events and notifies user.
//Updates tiles

(function () {
    "use strict";

    importScripts("//Microsoft.WinJS.0.6/js/base.js");

    //Begin task
    var backgroundTaskInstance = Windows.UI.WebUI.WebUIBackgroundTaskInstance.current;

    var notifications = Windows.UI.Notifications;

    var date = new Date();

    displayTileNotification(date);
    backgroundTaskInstance.succeeded = true;
    close();

    function displayTileNotification(content) {
        // get a filled in version of the template by using getTemplateContent
        var tileXml = notifications.TileUpdateManager.getTemplateContent(notifications.TileTemplateType.tileWideText01);

        // get the text attributes for this template and fill them in
        var tileAttributes = tileXml.getElementsByTagName("text");

        var title = "Tile Updated At";
        tileAttributes[0].appendChild(tileXml.createTextNode(title));
        tileAttributes[1].appendChild(tileXml.createTextNode(content));

        // create the notification from the XML
        var tileNotification = new notifications.TileNotification(tileXml);

        // send the notification to the app's default tile
        notifications.TileUpdateManager.createTileUpdaterForApplication().update(tileNotification);
    }

})();

Finally, you need to configure the manifest. Double-click package.manifest to bring up the wizard.

  1. In the Application UI tab, change Lock screen notifications to Badge and Tile Text
  2. Supply pointers to a wide tile image and badge image of the required sizes.
  3. In the Declarations tab, add a Background Task
  4. Select Timer
  5. Add backgroundtask.js in the field for Start Page

Run the program.  Click the button and the first time, you will be prompted to enable lock screen access.  Allow it.

Watch the Start Screen.  Find your tile and change it to wide format.  Wait.  The tile should update in 15-30 minutes then every 15 minutes thereafter even if the program is terminated.

 

 

Advertisements

3 Comments »

RSS feed for comments on this post. TrackBack URI

  1. hey i get a class not registered error when the code reached builder.register. what am i doing wrong could you please help me out.

  2. If your background.js file is in the js folder of your solution, make sure that in the manifest, the StartPage entry is js\backgroundtask.js


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Blog at WordPress.com.
Entries and comments feeds.

%d bloggers like this: