HTML5 Zone is brought to you in partnership with:

Clark is a web evangelist for Microsoft based in Illinois. A Chicago native who can’t spell, Clark as a kid actually made his money building cars, getting grease under his nails. That art of building would later lead him to software development where he drinks the Web Development Kool-Aid. Writing code is what keeps Clark awake at night, while continually working on his craft and rapping with others over a few cold CORS. You can hear Clark muse about software on his podcast Developer Smackdown, or find his family cruising around in a 1968 Camaro SS. Clark is a DZone MVB and is not an employee of DZone and has posted 32 posts at DZone. You can read more from them at their website. View Full User Profile

31 Days of Windows 8 for HTML5 | Day #11: Lock Screen Apps

11.16.2012
| 3218 views |
  • submit to reddit

 This article is Day #11 in a series called 31 Days of Windows 8.  Each of the articles in this series will be published for both HTML5/JS and XAML/C#. You can find additional resources, downloads, and source code on our website.

advertisementsample

Today we cover another part of notifications in Windows 8: the Lock Screen.  If you’re running Windows Phone or Windows 8 on your machine, you’ve likely gotten pretty familiar with the lock screen.  It shows you how many emails you’ve received, Facebook messages, the clock, and your connectivity status.  Here’s my current lock screen:

day11-7

Yes, that’s a photo of my screen. I have no clue how to take a screen shot of my lock screen without a VM installed. Anyways, you can also see that I’m only writing this article a few days ahead of publication time, and someone has left me a number of instant messages.

We, as developers, have the ability to add our badges to this lock screen as well, but it’s dangerous to go alone.  Take this.  It’s Microsoft’s guidance on the best ways to utilize the Lock Screen notification area.

Configuring our Manifest

To get started the first thing we need to do is configure out application for lock screen notifications. We do that in where? Yes, our package.appxmanifest file under the Application UI / Notification Section. We’re going to set the Lock Screen Notifications to either Badge or Badge and Tile Text. What’s the difference? A Badge would update the lock screen and your tile while Badge and Tile Text would update that + putting a text notification on the front screen if the user selects your app. This is something that appears to be only set from the manifest and by the user. For today let’s go all out and select the Badge and Tile Text option.

image

Well that fired off a slew of validation errors huh. You’ll notice the screen is now lit up with red X symbols.  When lock screen notifications are enabled, we are required to have a Badge Logo ( we created a new 24×24 png for this which has to be transparent white png ), and since we chose the option that includes tile updates as well, we’re required to provide a Wide Logo image as well.  Here’s my Application UI tab with those files added:

image

Wait, what? Why still red? Well “If lock screen notifications are enabled, you must specify one or more Background task declarations of type ‘Timer’, ‘Control channel’, or ‘Push notification.’”

What this means is that Lock Screen apps generally expect to be updated from a Background Agent.  Let’s flip over to our Declarations tab, and add a Background Task. We’re going to add support for push notifications and add our default page as the entry point:

image

In my example app, we’re not actually going to create a background task, however.  I’m going to cover that extensively tomorrow.  Instead, we’re going to focus specifically on the processes and code that allows us to update our Lock Screen information.

Asking for Permission

Before you can ever start thinking about writing content to the user’s lock screen, you need to ask for their permission.  Now, you don’t HAVE to ask, but without asking their permission, the road to the Lock Screen is perilous and fraught with danger.  Here’s what I mean:

You get ONE, and only ONE opportunity to ask the user for permission to be on their lock screen. 

If you ask once, and they say “Don’t Allow”, you’re not even capable of asking again. 

Here’s what it looks like when you ask:

image

And here’s how you do it:

var background = Windows.ApplicationModel.Background;
var promise = background.BackgroundExecutionManager.requestAccessAsync();

If you never ask, the only way to get on the lock screen is for the user to open their PC Settings, and explicitly add you. How many users will really do that after the fact?

image

Users can select up to 7 apps to be displayed on their Lock Screen and *1* to display text.  We want to make sure we’re one of them.  So, because our status can change at the user’s whim, we should be responsible before trying to send updates to their Lock Screen.

Making Sure You Have Permission

This is not a required step.  You can have your app, or your background task (as we will cover tomorrow) continue sending updates even if you don’t have permission.  That being said, your updates also won’t ever be seen by the user.  Without permission, your updates will disappear into the ether.

Here’s how we check to see if the user has granted us permission to update the lock screen:

var background = Windows.ApplicationModel.Background;

var promise = background.BackgroundExecutionManager.requestAccessAsync().then(
    function (result) {
        switch (result) {
            case background.BackgroundAccessStatus.denied:
                // Background activity and updates DENIED 
                break;

            case background.BackgroundAccessStatus.allowedWithAlwaysOnRealTimeConnectivity:
                // Added to list of background apps.
                // Set up background tasks
                // CAN use the network connectivity broker.
                break;

            case background.BackgroundAccessStatus.allowedMayUseActiveRealTimeConnectivity:
                // Added to list of background apps.
                // Set up background tasks
                // CANNOT use the network connectivity broker.
                break;

            case background.BackgroundAccessStatus.unspecified:
                // The user didn't explicitly disable or enable access and updates. 
                break;
        }
    });

So at this point, we’ve covered asking the user for permission, and then checking to make sure that permission has been granted.  The next step is actually sending the update.

Updating the Lock Screen

Sending an actual update will look pretty familiar if you’ve read the previous two articles.  (Day #9 – Live Tiles, Day #10 – Toast Notifications)  Like those previous examples, we are grabbing a template that consists of XML (in this case, it’s incredibly simple):

<badge value="31"/>

Next, we need to specify the value that we want to display.  We have several options in this scenario.  Not only can we use any number from 1 – 99, but we also have a number of glyphs to choose from.  The best part is that the template is smart enough to recognize the difference, so the only thing that will change in our code is the actual value we pass in.  Here’s the code to make the update to the badge:

var notifications = Windows.UI.Notifications;

var template = notifications.BadgeTemplateType.badgeNumber;
var templateContent = notifications.BadgeUpdateManager.getTemplateContent(template);

var element = templateContent.selectSingleNode("/badge");
element.setAttribute("value", "31");

var update = new notifications.BadgeNotification(templateContent);
notifications.BadgeUpdateManager.createBadgeUpdaterForApplication().update(update);

Just like the tiles and toast I am setting an attribute on the badge element. In this case I am setting the value attribute to 31. That results in a Lock Screen badge that looks like this:

day11-1

If you would rather use one of the glyphs, here’s a list of what’s available, courtesy of the Badge overview page on MSDN.

11-XAML-GlyphList

To specify a glyph rather than a number, we only need to change the value attribute to the name of the glyph listed above.

//set
element.setAttribute("value", "alert");

//result
<badge value="alert"/>

That’s about it for Lock Screen apps… Overall this is pretty easy. We’re limited in what what we can display on the screen but if you’re awesome then maybe you’re up there. 

Wait… There’s a few more things. Let’s crawl into the weeds. 

When we started this article we jumped right into the app manifest file. The first thing we did was update the Lock Screen Notifications to chose “Badge and Tile Text” in our appxmanifest file, we enabled these Badges we’re creating to appear on our Tile as well.  (This is why the WideTile.png file was required.)  Here’s what my Live Tile looks like with that same “Playing” badge applied:

11-XAML-WideLogo 

Man that tile is just ugly but, ok you get the point. Initially I thought, sweet my work here is done, but something was bothering me. The word text in Badge and Tile Text. We really haven’t displayed any true text right? Turns out the story wasn’t done. If you’re setup for Tile updates you can actually have your app display those tile updates on the Lock Screen too. Wait, what?!!? Yep. Let’s go to: Setting –> Change PC Settings –> Personalize. Look really close at the bottom right hand side of the settings. Choose an app to display detailed status. Select that guy and your app should be listed in the menu. Choose it! Right now!

image

After doing so, when your app is running your tile text will also show up on the screen. Check out the sauce there.

day11-3

But wait, who is the lucky winner? I guess that is for you to choose. It appears that your app has no rights to even put itself in that box.

- read this -

Now during the course of writing this there were a few things that I came across.

#1: setTimeout is your friend at least when trying to manually test this. To see what was going to get displayed on the lock screen, I created a silly button in my app. The handler for my button looked like such:

clearNotifications();

setTimeout(function () {
    sendBadgeUpdateXML();
}, 5 * 1000);

setTimeout(function () {
    sendTileUpdate();
}, 6 * 1000);

This allowed me the time to fire off the events and lock the machine. Then I could sit back and watch the magic happen.

#2: There are “three” different ways to fire off badge updates. Why you ask? No clue. The all seem to work the same regardless. First there are two templates:

var template = notifications.BadgeTemplateType.badgeGlyph;

var template = notifications.BadgeTemplateType.badgeNumber;

As the templates would imply, one is for the number and one for the glyph. That is a bit confusing when you know that the xml is just:

<badge value="31"/>

Turns out, it just doesn’t matter which one you pick. They act the same. Maybe down the road this will have more relevance so I would use what  you want to “semantically” do.

So that was 2 different ways. What the third. Well just raw XML manipulation.

var badgeXmlString = "<badge value='alert'/>";

var badgeDOM = new Windows.Data.Xml.Dom.XmlDocument();
badgeDOM.loadXml(badgeXmlString);

var notifications = Windows.UI.Notifications;
var badge = new notifications.BadgeNotification(badgeDOM);
notifications.BadgeUpdateManager.createBadgeUpdaterForApplication().update(badge);

It’s straight forward and works but you pick your poison.

Summary

We can update our Lock Screen information from our app at any time, but the tricky part is getting the user’s permission.  Once you’ve gotten that, updating the information is pretty simple, as we saw in this article.

If you would like to download a working application that uses the code from this article, click the icon below:

 downloadHTMLdownloadTheTools

Tomorrow, we’re going to wrap up the last three days by talking about Background tasks.  We’ll show how to update Live Tiles, Toast notifications, and Lock Screen data from a background task.  See you then!

Published at DZone with permission of Clark Sell, author and DZone MVB. (source)

(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)