Windows 8: Displaying a clock on Live Tiles

The application life cycle imposed upon developers by Windows 8 can be tricky. An app can only execute code while being in the visible foreground, with background tasks being the only exception. Those tasks have extremely limited resources, but are in addition to that not allowed to run at the developers discretion. A task has to be registered using one of the available triggers – for instance when Internet becomes available, an SMS message has been received or when a time zone change happens on the device used. A scenario that requires a background task to run in a timed and repeating manner is quite tricky: If the app is not put on the lock screen, a background task is only allowed to run every two hours. In addition, the only available timed trigger is the MaintenanceTrigger, which is only executed when the device is connected to AC power. Should the user put your app on the lock screen, the TimeTrigger can be used, which is probably exactly what you are looking for – could the trigger execute more frequently than every 15 minutes. Since it cannot, how can one do something as outlandish as putting a clock on a live tile?

While the solution to this problem might seem like a hack, it is merely a crafty best practice solution. While we have a quite rigid constraints for the frequency of our code execution, we can schedule notifications that are delivered whenever we deem it appropriate – and we can schedule a whopping 4096 of them.

The Code

The solution is thus quite simple. My app “Awesome World Time” first asks the user whether it can be added to the lock screen. This dialog is completely managed by Windows and simply has to be called. Windows will also make sure that the user is not asked too often should he choose to decline my request.

If the user accepts, I ask my controller for background tasks to register a timed background task, set to run at every 45 minutes under the condition that a user is present. Of course, before registering this task, one should check whether a task has already been registered and act accordingly.

The task itself consists of a simple iteration: It asks for every secondary tile pinned to the start screen, deletes all already scheduled notifications and creates two hours of notifications in advance – with each notification being active for exactly one minute. To keep this code clean and not too specific to its task, I removed all code used to do time zone magic.