7. 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
8. Typical aspects of the process lifecycle
1 app in the
foreground
System of app
events exists
User must be
unaware
Background
processing exists
9. The process lifecycle
Not running
Running
Suspended
Not running/
Terminated
Launching Suspending
Resuming
Termination
App Close
App crash
11. 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)
{ ... }
12. 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
13. 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
14. 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
19. 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!
23. 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
24. Building blocks of a background task
BackgroundTaskBuilder
MyBackgroundTask
IBackgroundTask
Trigger
Condition
TaskEntryPoint: MyBackgroundTask
25. Your background code
• A class which implements IBackgroundTask
public sealed class MyBackgroundTask: IBackgroundTask
{
public void Run(IBackgroundTaskInstance task)
{
// Insert background code
}
}
26. Triggers
• Background task only starts when a trigger is firing
• One task, one trigger
• Trigger is an “event” that happens in the system
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
27
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)
28
29. Conditions
• Can be added on trigger
• Trigger only fires when condition is true
• Can help not to waste valuable resources
32. 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();
}
33. 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
35. 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…)
40. 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
41. 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
46. Available triggers for lock screen apps
Push notification trigger
Control channel trigger
Time trigger
47. 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
48. 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();
49. When would you use this?
• Notify the client that action is required
51. 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
52. 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
53. 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
55. Windows 8 and alarms
• In Windows 8, it’s not possible to build an alarm app…
• Background process?
• Lock screen?
• Time trigger?
56. Windows 8.1 now has the Alarms App
• Can be an alarm clock, timer and stopwatch
57. 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
58. 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
59. Steps to Become an Alarm App
• Edit the manifest XML
• No option to do this from the manifest designer
59
<Extensions>
<Extension Category="windows.backgroundTasks"
EntryPoint="App">
<BackgroundTasks>
<Task Type="timer" />
</BackgroundTasks>
</Extension>
<m2:Extension Category="windows.alarm" />
</Extensions>
60. 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
63. 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
• …
64. 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
66. 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 X
HTTPS
X X
FTP
X
69. Transferring a file
private async void DownloadFile(Uri source, StorageFile destinationFile)
{
var downloader = new BackgroundDownloader();
var dl = downloader.CreateDownload(source,
destinationFile);
await dl.StartAsync();
}
70. 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
72. 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,
}
75. 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
76. 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…
78. 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
79. More info?
• Check out my Pluralsight course on this topic
http://gicl.me/PSWin8BGProc