A look behind the scenes: Windows 8 background
processingGill Cleeren@gillcleeren
About me…
• Gill Cleeren• .NET Architect @Ordina • Pluralsight trainer• Microsoft Regional Director• Client Dev MVP• Speaker • User group lead (www.visug.be) • Author • Blog: www.snowball.be• Email: [email protected] • Twitter: @gillcleeren
See my courses on Pluralsight!
• See my courses at
http://gicl.me/PluralsightCourses
Agenda
• Windows 8 lifecycle explained• Background processing options• Server-side• Background tasks• Lock screen apps• Alarm apps (new in Windows 8.1)• Geofencing (new in Windows 8.1)• Background transfers• Background audio
Q: Why do we need background APIs?A: The process lifecycle of Windows 8
Before Windows 8…
User was in control
Now, since Windows 8…
Windows 8 handles the process lifecycle itself• No dialogs• Give the user the best experience• App should give the impression it has
been running all the time
Typical aspects of the process lifecycle
1 app in the foreground
System of app events exists
User must be unaware
Background processing exists
The process lifecycle
Not running
Running
SuspendedNot running/ Terminated
Launching Suspending
Resuming
TerminationApp CloseApp crash
DemoThe Application-Circle-of-Life
It’s an event thing…
• Launched• Happens when user taps tile• PreviousExecutionState indicates if the app was
• Activation• Most often in combination with a contract
• Search• Share
• Doesn’t trigger the Launched event handler code!
protected override void OnLaunched(LaunchActivatedEventArgs args){ if (args.PreviousExecutionState ==
ApplicationExecutionState.Terminated) { ... }
It’s an event thing…
• Suspending• Last chance to save state• Apps won’t get suspended in critical code blocks• 5 seconds before suspending fires• 5 seconds to execute code
• Resuming• Can only happen is app is suspended, not terminated• Same memory instance• Immediate• Typical use: data-rehydration
App, you are… terminated!
• Termination• Not an event that we see in code• Triggered by Windows
• Low memory resources• Application closed by user• App crash• User logoff
State management
• Application events can be used to manage state• User must think that app has been running all the time
• Options:• SuspensionManager
• Available already in Windows 8• In Windows 8.1, integrated in NavigationHelper
• Application Data API• Local• Roaming
• Service• Time issues possible
DemoApplication events
Q: OK, what background processing options do we have?A: Quite a few actually! Let’s take a look!
Options for background processing
Server-side • Push notifications
Client-side
• Background tasks• Lock screen apps• Alarm apps• Geofencing• Background transfer• Background audio
Push notificationsServer-side
Push notifications
• WNS = Windows Notification Service• Allows delivery of tile and toast XML messages over the wire
• Can arrive when the app isn’t running• Create background processing without processing
• Happens on the server
• Transparent process for the developer• Free services
• Cloud-based so no worries on scalability• Easily updates millions of devices• Register your app in the store
• No need to publish!
• You can use Azure for every component• It’s recommended to do so even!
Push notification architectureWindows 8 Cloud Service
Windows Notification
Service
Modern UI App
NotificationClient Platform
2
3
1 3
1. Request Channel URI2. Register with your Cloud Service3. Authenticate & Push Notification
DemoPush notifications
Background tasksClient-side
Background tasks in general
• Balance between UX and hardware restrictions• Battery, network…
• Windows 8 locks down what apps can do in the background• An app can’t keep running when it’s not in the foreground• Only “small amounts of code” are possible• Constrained environment hard for some scenarios
• Typical uses• Download data from a service• Send notification to the user• …
• Run all the time• Once registered, run when app is running and when it’s not running
Building blocks of a background task
BackgroundTaskBuilder
MyBackgroundTask
IBackgroundTask
Trigger
Condition
TaskEntryPoint: MyBackgroundTask
Your background code
• A class which implements IBackgroundTask
public sealed class MyBackgroundTask: IBackgroundTask{ public void Run(IBackgroundTaskInstance task) { // Insert background code }}
Triggers
• Background task only starts when a trigger is firing• One task, one trigger• Trigger is an “event” that happens in the system
Control Channel
Push Notification Maintenance Timer System Event
27
New background events in Windows 8.1• BackgroundWorkCostChanged• Related to Background Work Costs• Based on what is scheduled, we can decide not to run our background task• This event allows you to change your background API strategy based on
what's currently going on with the system
• NfcStateChange• Allows your app to respond to near field communication (NFC) events for your
device even when the app isn't currently active
New in 8.1!
28
New background triggers in Windows 8.1• DeviceUseTrigger• Represents an event that an application can trigger to initiate a fixed-length,
long-running operation (content transfer, sync) with a device
• DeviceServicingTrigger• Represents an event that an application can trigger to initiate a long-running
update (firmware or settings) of a device
• … LocationTrigger (later)
New in 8.1!
Conditions
• Can be added on trigger• Trigger only fires when condition is true• Can help not to waste valuable resources
Internet Available /
Unavailable
Session Connected /
Disconnected
User Present / Not Present
Preparing your solution
• Registering a background task is done using Package manifest
Preparing your solution
One last thing before I’m deferred…
• If you have async code in the Run() of IBackgroundTask, you’ll need a deferral
public void Run(IBackgroundTaskInstance taskInstance){ BackgroundTaskDeferral deferral = taskInstance.GetDeferral();
// be awesome asynchronally
deferral.Complete();}
Constraints
• Background tasks are limited in the usage of• CPU
- Network- Not constrained when running on AC power- Modeled as the amount of energy the network is used to transfer bytes
- Not based on throughput
• Critical tasks receive guaranteed application resource quotas
CPU resource quota Refresh period
Lock screen app 2 CPU seconds 15 minutes
Non-lock screen app 1 CPU second 2 hours
Demo:Working in the background
Tomorrow in the office…Debugging background tasks is time consuming, boss. I have to toggle my
internet connection every time.
What? Didn’t you attend the user group talk on background tasks in WinRT??
Can’t say I did…(leaves the room quietly…)
Clearly this is not a conversation
you’ll have!
Debugging background tasks
Make sure the names match!
Manually trigger from Visual Studio
Demo:Working Debugging in the background
The
screen
The lock screen and lock screen apps• A set of APIs only available when the user puts the app on the lock
screen• WNS (Push Notifications): RAW notification that can trigger code execution• Network Trigger: constant connection• Time trigger: execute code at specific intervals
• Less constraints• Apps can become a lock screen only by using these triggers• Not every app should be on the lock screen!• An app can only ask once• User can enable/disable it through Permissions settings pane
The lock screen and lock screen apps• Only 7 apps can be on the lock screen• User-managed• App should be able to function if not on the lock screen too
• When on the lock screen:• Can update the badge• Display tile if promoted• Display toast that opens the app after login
Demo:Take a loOk at the loCk screen
Creating a lock screen app
• Step 1: Include a background task that requires lock screen permission
Creating a lock screen app
• Step 2: add required logos (manifest)• Lock screen badge logo• Wide logo for the app
• Step 3: enable lock screen notifications in manifest
Demo:Creating a lock screen app
Available triggers for lock screen apps
Push notification trigger
Control channel trigger
Time trigger
Push notification trigger
• WNS: allows sending push updates• Templated XML only
• Push Notification Trigger enables triggering a background task AND receiving just any string• RAW notification• 5K max
• All apps use same open connection• Efficient• No extra open sockets• App can still update lock screen or trigger code
• Delivered on best-effort basis
Steps to enable the Push Notification trigger• On the client• Channel URI• Background task• Push Notification trigger
• On the server• Authenticate• Send any string to client (raw notification)
PushNotificationTrigger pushNotificationTrigger = new PushNotificationTrigger();
When would you use this?
• Notify the client that action is required
Email is availableIncoming
communication message
Notify client that it needs to sync
data
Demo: Raw notifications
Network trigger
• If server-side can’t use WNS, we need to fall back on sockets• Open connection in the background• Complex to create• Not good for battery• Guaranteed delivery
Network trigger
• 2 types exist• Control channel trigger
• Required• Persistent connection between client and server• Initiated by the client• Maintained by Windows even when the app is in the background
• Keep-alive trigger • Optional• Client can send keep-alive messages even when in background
Time trigger
• Can run code based on time interval• Minimum is 15 minutes
• Requires app to be on the lock screen• Code ignored if not
• Requires manifest change to use Timer• Useful for POP3 mail checks, perform a service call
DemoTime trigger
Windows 8 and alarms
• In Windows 8, it’s not possible to build an alarm app…• Background process?• Lock screen?• Time trigger?
Windows 8.1 now has the Alarms App• Can be an alarm clock, timer and stopwatch
New in 8.1!
So, there’s a way now!
• Windows 8.1 adds the ability to make an app the Alarm app• Can show toasts (including sound) at specific time
• Precise to the second
• When the app is the alarm app, it can show special toast messages
New in 8.1!
Steps to Become an Alarm App
• Make the app lock-screen enabled• Select the Timer, Control channel
or Push Notification
• Make the app Toast capable• Define a badge logo
New in 8.1!
59
Steps to Become an Alarm App
• Edit the manifest XML• No option to do this from the manifest designer
<Extensions> <Extension Category="windows.backgroundTasks" EntryPoint="App"> <BackgroundTasks> <Task Type="timer" /> </BackgroundTasks> </Extension> <m2:Extension Category="windows.alarm" /></Extensions>
New in 8.1!
Steps to Become an Alarm App
• Request alarm access from the app• Use the AlarmApplicationManager.RequestAccessAsync()
• Create the scheduled toast notification• Set Duration to Long• Add custom commands (snooze and dismiss)
• Specify the snooze interval
New in 8.1!
Demo: ALAAAARM!!!
Geofencing
Coffeehouse
Works with GPS, Wi-Fi or IP address
New in 8.1!
Usages for geofencing
• “Remember the milk!”• Let the user know about delays at his (train)station• Check in on FourSquare automatically• Coupon-codes for stores• Virtual tour guide• …
New in 8.1!
Steps to Enable Geofencing in Your App • App must have required permissions• In the manifest, app must have a Location task• Containing a background task is therefore required• Must have lock-screen permissions
• Can prompt the user, only once though• Afterwards, still possible from Settings
• Setting up the geofence• Only circular fences are supported
• Contains latitude, longitude and radius• Get in notifications when entering or leaving the geofence
New in 8.1!
Demo:Geofencing
BackgroundTransfer API
• Allows uploading and downloading (large) files from outside the app• Runs when app is suspended
• Download is performed in a separate process• BackgroundTransferHost.exe
• Lives in Windows.Networking.BackgroundTransfer namespace• BackgroundDownloader & BackgroundUploader
Protocol Upload Download
HTTP X XHTTPS X XFTP X
BackgroundTransfer API
• Handles network status changes and glitches• Auto recovery
• Other supported features
Basic server credentials Proxy credentials Cookies Custom HTTP
headers
Flow to transfer files
BackgroundDownloader
Download Operation
Progress
ControlStartPause
ResumeStartAsync()
Transferring a file
private async void DownloadFile(Uri source, StorageFile destinationFile){ var downloader = new BackgroundDownloader(); var dl = downloader.CreateDownload(source, destinationFile);
await dl.StartAsync();}
Background Transfer Updates
• BackgroundTransferGroup allows apps to group transfer and change their priority• Do downloads in parallel or serial
• Possible to use a tile or toast update with the status of the transfer• BackgroundDownloader and BackgroundUploader have been extended
• FailureTileNotification • FailureToastNotification • SuccessToastNotification • SuccessTileNotification
New in 8.1!
Demo:Transferring files
Playing audio in the background
• Audio can be played using the MediaElement• Pauses the playback when app is suspended
• MediaElement defines AudioCategory property• 2 options exist to enable
background audio public enum AudioCategory{ Other = 0, ForegroundOnlyMedia = 1, BackgroundCapableMedia = 2, Communications = 3, Alerts = 4, SoundEffects = 5, GameEffects = 6, GameMedia = 7,}
Register from transport controls
Play / Pause
Next / Previous Track
Sound Level
Audio Information
Register for transport controls
• In Windows 8: • Register for MediaControl events
• PlayPauseTogglePressed• PlayPressed• PausePressed• StopPressed • (optional) SoundLevelChanged
• Option will probably be discontinued after Windows 8.1
Register for transport controls
• In Windows 8.1• Use the SystemMediaTransportControls
• Not a static class that exposes events• Can be accessed through the GetForCurrentView static method• All events are processed through the single ButtonPressed event• Offers more options
• Record, rewind…
Demo:Playing music in the background
Summary
• Background processing in Windows 8 is limited and constrained• Different approach than in previous editions• Background tasks and lock screen apps allow to run small blocks of
code• Downloading in the background and playing audio is supported
More info?
• Check out my Pluralsight course on this topic
http://gicl.me/PSWin8BGProc
Q&A
Thanks!
A look behind the scenes: Windows 8 background
processingGill Cleeren@gillcleeren