A look behind the scenes: Windows 8 background processing

82
A look behind the scenes: Windows 8 background processing Gill Cleeren @gillcleeren

description

Gill Cleeren's slides from his presentation on Background Tasks in Windows 8.1 - Presented to Windows Phone User Group London: July 30th 2014

Transcript of A look behind the scenes: Windows 8 background processing

Page 1: A look behind the scenes: Windows 8 background processing

A look behind the scenes: Windows 8 background

processingGill Cleeren@gillcleeren

Page 2: A look behind the scenes: Windows 8 background processing

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

Page 3: A look behind the scenes: Windows 8 background processing

See my courses on Pluralsight!

• See my courses at

http://gicl.me/PluralsightCourses

Page 4: A look behind the scenes: Windows 8 background processing

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

Page 5: A look behind the scenes: Windows 8 background processing

Q: Why do we need background APIs?A: The process lifecycle of Windows 8

Page 6: A look behind the scenes: Windows 8 background processing

Before Windows 8…

User was in control

Page 7: A look behind the scenes: Windows 8 background processing

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

Page 8: A look behind the scenes: Windows 8 background processing

Typical aspects of the process lifecycle

1 app in the foreground

System of app events exists

User must be unaware

Background processing exists

Page 9: A look behind the scenes: Windows 8 background processing

The process lifecycle

Not running

Running

SuspendedNot running/ Terminated

Launching Suspending

Resuming

TerminationApp CloseApp crash

Page 10: A look behind the scenes: Windows 8 background processing

DemoThe Application-Circle-of-Life

Page 11: A look behind the scenes: Windows 8 background processing

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) { ... }

Page 12: A look behind the scenes: Windows 8 background processing

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

Page 13: A look behind the scenes: Windows 8 background processing

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

Page 14: A look behind the scenes: Windows 8 background processing

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

Page 15: A look behind the scenes: Windows 8 background processing

DemoApplication events

Page 16: A look behind the scenes: Windows 8 background processing

Q: OK, what background processing options do we have?A: Quite a few actually! Let’s take a look!

Page 17: A look behind the scenes: Windows 8 background processing

Options for background processing

Server-side • Push notifications

Client-side

• Background tasks• Lock screen apps• Alarm apps• Geofencing• Background transfer• Background audio

Page 18: A look behind the scenes: Windows 8 background processing

Push notificationsServer-side

Page 19: A look behind the scenes: Windows 8 background processing

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!

Page 20: A look behind the scenes: Windows 8 background processing

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

Page 21: A look behind the scenes: Windows 8 background processing

DemoPush notifications

Page 22: A look behind the scenes: Windows 8 background processing

Background tasksClient-side

Page 23: A look behind the scenes: Windows 8 background processing

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

Page 24: A look behind the scenes: Windows 8 background processing

Building blocks of a background task

BackgroundTaskBuilder

MyBackgroundTask

IBackgroundTask

Trigger

Condition

TaskEntryPoint: MyBackgroundTask

Page 25: A look behind the scenes: Windows 8 background processing

Your background code

• A class which implements IBackgroundTask

public sealed class MyBackgroundTask: IBackgroundTask{ public void Run(IBackgroundTaskInstance task) { // Insert background code }}

Page 26: A look behind the scenes: Windows 8 background processing

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

Page 27: A look behind the scenes: Windows 8 background processing

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!

Page 28: A look behind the scenes: Windows 8 background processing

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!

Page 29: A look behind the scenes: Windows 8 background processing

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

Page 30: A look behind the scenes: Windows 8 background processing

Preparing your solution

• Registering a background task is done using Package manifest

Page 31: A look behind the scenes: Windows 8 background processing

Preparing your solution

Page 32: A look behind the scenes: Windows 8 background processing

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();}

Page 33: A look behind the scenes: Windows 8 background processing

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

Page 34: A look behind the scenes: Windows 8 background processing

Demo:Working in the background

Page 35: A look behind the scenes: Windows 8 background processing

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!

Page 36: A look behind the scenes: Windows 8 background processing

Debugging background tasks

Make sure the names match!

Page 37: A look behind the scenes: Windows 8 background processing

Manually trigger from Visual Studio

Page 38: A look behind the scenes: Windows 8 background processing

Demo:Working Debugging in the background

Page 39: A look behind the scenes: Windows 8 background processing

The

screen

Page 40: A look behind the scenes: Windows 8 background processing

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

Page 41: A look behind the scenes: Windows 8 background processing

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

Page 42: A look behind the scenes: Windows 8 background processing

Demo:Take a loOk at the loCk screen

Page 43: A look behind the scenes: Windows 8 background processing

Creating a lock screen app

• Step 1: Include a background task that requires lock screen permission

Page 44: A look behind the scenes: Windows 8 background processing

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

Page 45: A look behind the scenes: Windows 8 background processing

Demo:Creating a lock screen app

Page 46: A look behind the scenes: Windows 8 background processing

Available triggers for lock screen apps

Push notification trigger

Control channel trigger

Time trigger

Page 47: A look behind the scenes: Windows 8 background processing

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

Page 48: A look behind the scenes: Windows 8 background processing

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();

Page 49: A look behind the scenes: Windows 8 background processing

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

Page 50: A look behind the scenes: Windows 8 background processing

Demo: Raw notifications

Page 51: A look behind the scenes: Windows 8 background processing

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

Page 52: A look behind the scenes: Windows 8 background processing

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

Page 53: A look behind the scenes: Windows 8 background processing

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

Page 54: A look behind the scenes: Windows 8 background processing

DemoTime trigger

Page 55: A look behind the scenes: Windows 8 background processing

Windows 8 and alarms

• In Windows 8, it’s not possible to build an alarm app…• Background process?• Lock screen?• Time trigger?

Page 56: A look behind the scenes: Windows 8 background processing

Windows 8.1 now has the Alarms App• Can be an alarm clock, timer and stopwatch

New in 8.1!

Page 57: A look behind the scenes: Windows 8 background processing

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!

Page 58: A look behind the scenes: Windows 8 background processing

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!

Page 59: A look behind the scenes: Windows 8 background processing

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!

Page 60: A look behind the scenes: Windows 8 background processing

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!

Page 61: A look behind the scenes: Windows 8 background processing

Demo: ALAAAARM!!!

Page 62: A look behind the scenes: Windows 8 background processing

Geofencing

Coffeehouse

Works with GPS, Wi-Fi or IP address

New in 8.1!

Page 63: A look behind the scenes: Windows 8 background processing

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!

Page 64: A look behind the scenes: Windows 8 background processing

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!

Page 65: A look behind the scenes: Windows 8 background processing

Demo:Geofencing

Page 66: A look behind the scenes: Windows 8 background processing

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

Page 67: A look behind the scenes: Windows 8 background processing

BackgroundTransfer API

• Handles network status changes and glitches• Auto recovery

• Other supported features

Basic server credentials Proxy credentials Cookies Custom HTTP

headers

Page 68: A look behind the scenes: Windows 8 background processing

Flow to transfer files

BackgroundDownloader

Download Operation

Progress

ControlStartPause

ResumeStartAsync()

Page 69: A look behind the scenes: Windows 8 background processing

Transferring a file

private async void DownloadFile(Uri source, StorageFile destinationFile){ var downloader = new BackgroundDownloader(); var dl = downloader.CreateDownload(source, destinationFile);

await dl.StartAsync();}

Page 70: A look behind the scenes: Windows 8 background processing

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!

Page 71: A look behind the scenes: Windows 8 background processing

Demo:Transferring files

Page 72: A look behind the scenes: Windows 8 background processing

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,}

Page 73: A look behind the scenes: Windows 8 background processing
Page 74: A look behind the scenes: Windows 8 background processing

Register from transport controls

Play / Pause

Next / Previous Track

Sound Level

Audio Information

Page 75: A look behind the scenes: Windows 8 background processing

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

Page 76: A look behind the scenes: Windows 8 background processing

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…

Page 77: A look behind the scenes: Windows 8 background processing

Demo:Playing music in the background

Page 78: A look behind the scenes: Windows 8 background processing

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

Page 79: A look behind the scenes: Windows 8 background processing

More info?

• Check out my Pluralsight course on this topic

http://gicl.me/PSWin8BGProc

Page 80: A look behind the scenes: Windows 8 background processing

Q&A

Page 81: A look behind the scenes: Windows 8 background processing

Thanks!

Page 82: A look behind the scenes: Windows 8 background processing

A look behind the scenes: Windows 8 background

processingGill Cleeren@gillcleeren