7. Apps do not get notified when
they are getting terminated
8. Registering for Suspend and Resume is
Easy
//Register for the Suspending event and call suspendingHandler when received
Windows.UI.WebUI.WebUIApplication.addEventListener("suspending", suspendingHandler);
//Handle the suspending event and save the current user session using WinJS sessionState
function suspendingHandler(eventArgs) {
//We are getting suspended
}
//Register for the Resuming event and call resumingHandler when received
Windows.UI.WebUI.WebUIApplication.addEventListener("resuming", resumingHandler);
function resumingHandler(
) {
//We are getting resumed, in general do nothing
}
9. Registering for Suspend and Resume is
Easy
// Register for the Suspending event and call OnSuspending when received
// Handle the suspending event and save the current user session using WinJS sessionState
void async
var
//TODO: Save application state and stop any background activity
}
// Register for the Resuming event and call OnResuming when received
void
object
object
{
// We are getting resumed, in general do nothing
}
23. Example
System Trigger
Register on User Login
using Windows.ApplicationModel.Background;
// Specify the trigger
IBackgroundTrigger trigger =
new SystemTrigger(SystemTriggerType.SessionConnected, false);
Create user
login trigger
Associate
trigger with
app code
// Associate app code with the trigger
BackgroundTaskBuilder taskBuilder = new BackgroundTaskBuilder();
taskBuilder.TaskEntryPoint = “MyApp.Background.RegisterForUserLogin";
taskBuilder.SetTrigger(trigger);
taskBuilder.Name = “OnUserPresent";
Register
// Register the task for background execution
trigger
IBackgroundTaskRegistration taskRegistration =
taskBuilder.Register();
24. Example
System Trigger
Background execution on User
Login
using Windows.ApplicationModel.Background;
namespace MyApp.Background
{
public sealed class RegisterForUserLogin: IBackgroundTask
{
public void Run(IBackgroundTaskInstance taskInstance)
{
// Your app code
}
}
}
25. Trigger
Lock screen
Description
UserPresent
X
User becomes present (touches screen, keyboard, mouse)
UserAway
X
User becomes absent or system idle timer expires.
SessionConnected
X
User logs in.
ControlChannelReset
X
Control channel is reset
InternetAvailable
Internet becomes available
NetworkStateChange
Change in connection state (cost, network)
ServicingComplete
App update has finished
OnlineIdConnectedStateChange
Microsoft account connected to logon account has changed.
LockScreenApplicationAdded
An app has been added to the lock screen
LockScreenApplicationRemoved
An app has been removed from the lock screen
TimeZoneChange
The system time zone has changed
SmsReceived
SMS message received by mobile broadband device.
BackgroundWorkCostChange
X
the cost of background work changes
30. var t = new SystemTrigger(SystemTriggerType.NetworkStateChange, false);
var btb = new BackgroundTaskBuilder() {
TaskEntryPoint = "BGComponent.BTC",
Name = "NetworkState Changed" };
btb.SetTrigger(t);
SystemCondition c = new SystemCondition(SystemConditionType.UserPresent);
btb.AddCondition(c);
BackgroundTaskRegistration task = btb.Register();
33. •
Hardware includes low-power
DRAM, busses, and devices
•
Always connected to the internet
•
App experiences are always fresh
and up to date
•
Transitions instantly between on
and off states (phone-like
behavior)
Requires very low idle
power to enable
Connected Standby
34. • How does this work
in connected standby?
Mobile broadband
Network
(e.g. 3G, 4G, LTE, etc.)
Connectivity
• Nothing special,
one model to stay
connected.
• Need a hardware slot
35. •
Implement a Cancel handler. Cancel all outstanding tasks by using
CancelationTokenSource
See the following links for more details:Application lifecycle (Metro style apps): http://msdn.microsoft.com/en-us/library/windows/apps/xaml/hh464925.aspxGuidelines for app suspend and resume (Metro style apps): http://msdn.microsoft.com/en-us/library/windows/apps/hh465088.aspxForcing Metro Apps to terminate: http://iinspectable.wordpress.com/2012/07/08/forcing-metro-apps-to-terminate/
WSA = one foreground full screen window that allows the user to work more efficientlyNon-visible WSAs are quickly suspended to preserve battery lifeAs a developer, you have to know how Windows manages your App lifetime and how to be a good citizen
Demonstrate basic task switchingLaunch Weather: it takes full screen and there is no other App visibleLaunch Calendar: Weather is now running in the background but not for longShow task manager.Make sure you have selected View | Status Values | show Suspended StatusWait for Weather to suspendNOTE: click on the Status column to sort and see all the suspended AppsIt is still possible to run in the background in very specific cases: Launch Music and play a songShow task manager where Music is never suspendedRead http://blogs.msdn.com/b/b8/archive/2012/02/07/improving-power-efficiency-for-applications.aspx for more details about what is possible to run in the background with WinRTExplain that the system did all the work:Threads are suspended at Kernel level: no CPU is granted but memory is still thereThe App is still visible through Windows+TAB task list and “restart” instantlyLast but not least, Windows can decide to “terminate” any App in low memory conditions. Read http://iinspectable.wordpress.com/2012/07/08/forcing-metro-apps-to-terminate/ for more details + the ByeBye tool for the demo
Apps get 5 seconds to handle suspension (save state etc.) Potentially a little more if there is I/O contentionYou will see that apps get into the suspended state after about 10 seconds.You can check it if you launch an App in Snap view and keep the Task Manager in the Filled view)Suspended Apps are notified before being suspendingAfter that event, no more CPU for the application threadsIf you take too long to suspend… you’ll get terminatedWindows is free to “terminate” any WSA if memory pressure is detectedApps are not notified before being terminatedSee http://msdn.microsoft.com/en-us/library/windows/desktop/aa366541(v=vs.85).aspx for API to use to detect when memory is running high/lowSee http://blogs.msdn.com/b/b8/archive/2012/04/17/reclaiming-memory-from-metro-style-apps.aspx for details about memory management based on Working Set metrics in Windows
= “tombstoning” in Windows phone (read http://msdn.microsoft.com/en-us/library/ff817008(v=vs.92).aspx for the execution model in WP)This also visible with SysInternals Process Explorer (http://technet.microsoft.com/en-us/sysinternals/bb896653.aspx) where you see the same “Suspended” in the CPU column. It was possible to “suspend” a process in Windows 7 with Process Explorer: this is now done by Windows itself for WSAs.NOTE: Process Explorer is fully aware of WSAs = “Immersive” has new blue color. See Options | Configure Colors | Immersive Process + see package in tooltipWhen you right-click | Resume on a Suspended Metro App, it gets back automatically Suspending immediately by Windows
The user can still decide to explicitly “close”/”end” an App by using ALT+F4In 8.1 the drag/drop touch gesture (“drag the top of the App and drag it down to the bottom of the screen”) suspends the app. (although it is removed from the ALT-TAB backstack)The system is also allowed to “terminate” the apps.. [users can do it too via task manager or Process Explorer]There is no event fired during termination… you should save all your stuff by “suspending” or when possible, along the user navigation in the AppDEMO: use ByeBye tool from http://iinspectable.wordpress.com/2012/07/08/forcing-metro-apps-to-terminate to consume as much memory (working set) as possible and see that first the Immersive App working set are trimmed and then some Apps get terminatedWatch http://channel9.msdn.com/Events/TechEd/NorthAmerica/2011/WCL405 for Mark Russinovich talk about Windows memory management
Suspending:You have 5 seconds real time (not CPU time) to save what you need to save. If you take too long, the App will be terminated. Deferral here means telling the OS you are doing some async tasks; not that you want to get more than 5 sec time.In 8.1 Suspending happens with low priority (low I/O, lower thread priority) Suspend time compensates for this. Resuming:Sometimes useful for checking for updates in case of a News, weather, stocks App for example.Ex: you’ve stored the time of suspension and, on resuming, if there are more than x hours since then, the code checks for News updates.NOTE: when the App gets suspended, all the event handlers are still registered (sockets, system related,…) but will never get any CPU to run even if such an event occurs. So on resume you need to check your network, sockets, etc.
Suspending:You have 5 seconds real time (not CPU time) to save what you need to save. If you take too long, the App will be terminated. Deferral here means telling the OS you are doing some async tasks; not that you want to get more than 5 sec time. Note the async keyword to indicate we’re going to call awaitable I/O functions. Resuming:Sometimes useful for checking for updates in case of a News, weather, stocks App for example.Ex: you’ve stored the time of suspension and, on resuming, if there are more than x hours since then, the code checks for News updates.NOTE: when the App gets suspended, all the event handlers are still registered (sockets, system related,…) but will never get any CPU to run even if such an event occurs. So on resume you need to check your network, sockets, etc.
Create a new grid app from VSRun and navigate to a detail pageSuspend and shutdown from VS toolbarStart back up and show the app is back in detail pageUse PLM Basics to demo basic suspend and resume.Show suspend and resume from the debuggerDebug | Suspend / Resume / Resume and shutdownNotice when you suspend the progress bar stops moving Show terminated via the debugger or via the ByeBye toolsNOTE: it is complicated to get a previous Terminated state… (does not work via Task Manager wait suspend + Terminate we get NotRunning). Need to start the App and start the same App via VS or use the Debug | Suspend + Resume and shutdown or use ByeByeNOTE: 5 seconds to save state in Suspending event look at SuspendingOperation.Deadline as a hint readonlySee the following links for more details:HTML:http://msdn.microsoft.com/en-us/library/windows/apps/hh770838.aspxXAML: http://msdn.microsoft.com/en-us/library/windows/apps/xaml/Hh770837(v=win.10).aspx
Don’t wait until Suspending to save Settings or navigation informationNote: settings should apply immediately so… save them immediately too :^)XAML: new VS template implementation in Common\SuspensionManager to save the Frames navigation state
Third row is key point of the slide. The whole reason we save during suspend is so that we can come back to that state on relaunch (not resume). On Resume an app can check if its data is stale. E.g. a news app that has not been used for 2 weeks, might want to update is front page.
In Windows 8, you need to understand how you are activated. Some activations (e.g. Share) are not launching the full app. Main/secondary Tiles, Share, File Picker, file association…
TODO: review for RTM version!!!
OnLaunched is not triggered if activated by contracts
Dont’ show thisdemo if the Lesson #6 about contracts has been alreadydelivered-------------------------------------------------------------------------------------------Show Contoso Recipes demo for C# and “06 - Contracts\Demos\1_Search\JavaScript” otherwiseUse this as an opportunity to show them how the debugger in Visual studio can attach to a process.To show this option:go into Project -> Properties -> Debugging … Check “Do not launch, but debug my code when it starts”Now you can start the debugger… but nothing will happen until you use a way to activate the App (search, share target, secondary tile…)NOTE: in case of light dismissed UI like the Share target, put a breakpoint in the UI code in order to avoid being dismissed during the switch to the debugger
DebugContosoLaunch the app from Search contract (ensure it is not already running)Set a breakpoint in OnSearchActivated and OnLaunched (the latter is never hit)set a breakpoint in OnSuggestionRequested just once to avoid being stopped on each characterStep through the code. show the parameters that get passed Open the search charm. Search for “French” or “Mexican” or what ever ( salt, pepper) .. See the breakpoint hit.. Don’t forget to show how the debugger in Visual studio can be attached to a process before being activated:go into Project -> Properties -> Debugging … Check “Do not launch, but debug my code when it starts”Now you can start the debugger… [but nothing will happen]
TODO: check with RTM!!!
Splashscreen and background colors are set in the App manifest.It’s used by Windows to display the first screen before the App code starts to runSame during activation through ContractsLast bullet is only if the user moves away from the splash screen. Also WACK requirement is 5 seconds.
…but thisis not recommandedbecause not user friendlyHowever, sometimes… youdon’treally have the choice.I’veseendifferentideas to avoid the extendedsplashscreen; mostlyadding the progressinside the Main page. It is important becausewhenyouneed an Internet connection and itis not there, youdon’treallywant to bestuck in an extendedsplashscreenhelpless.Instead, show the connectionerror as embeddedtext in the main screen and provide a « retry » button.If youdon’t do that: thereisonly one choiceleft to the user… ALT+F4 NOTE: try to cache the data that you took forever to fetch; this will avoid the same wait next time the App is launched
Splash Screen Sample: http://code.msdn.microsoft.com/windowsapps/Splash-screen-sample-89c1dc78Run sampleTalk about notification and coordinate retrievalShow sys splash object retrieval in App.xaml.cs and passing through constructorAlso show event registration for system splash screen dismissalShow initialization in ExtendedSplash.xaml.csTODO: same for JavaScript?!!!
Some scenario require to be able to execute code even though the App is not running in the foreground
Show the Declarations tab of the manifest. Add a background task. Discuss all the checkboxesDiscuss each.Audio is different and not a background task like the others with a trigger. Will discuss in mediaControl channel is for Network protocols: Voip, IM etc. System triggers can be a wide variety: login, network change, timezone change, etc. Timer for periodic triggersPush Notification Trigger can be used with WNS “raw”New is location trigger. It allows to set up a trigger based on GPS or location dataMissing is Maintenance trigger. It works like Time, but no lock screen requirement and will not run on battery
Demo (previous slide) Requirements for non-lock screen app triggers (such as system).
Animated slide:Your app registers trigger with windowsApp can be suspended (fade to 50% transparent)App can terminated (app block disappears)Trigger (lightning) firesWindows creates the processLoads up the WInRT componentCalls Run()Background process is torn down.
@ 30:59System trigger api. This is session start.
Most of these are pretty self explanatory. Some require a little explanationServicingCompleteLockScreenApplicationAdded/Removed (important for Connected Standby and hardware slots)Draw the distinction between lock screen and non-lock screen trigger. BackgroundWorkCostChange is new for 8.1:BackgroundWorkCostChange is used to indicate when a system condition changes. This is to allow an app to differentiate between for example being on battery or connected standby or on AC. When on AC, a background task can do a lot more. (On win8, this was somewhat the case too since the global pool would adapt to system changes. However this was completely opaque to the app and app had to assume worst condition). When the trigger fires, a task can use the BackgroundWorkCost class to query the current cost of the background task. You need to be a lock screen app to get BackgroundWorkCostChange. There are 3 values for work cost. Low is for DC, medium and high depend on the status of the global pool.
Apps with background task on the lockscreen seen from a Users perspectiveIcons indicate status with badges. This has some additional manifest requirements (see later)Can have up to 7 apps (6+1 very special next to clock). This is to limit the number of critical background tasks. User can configure the most important apps for the lock screen in control panel.System makes a distinction between hardware slots and software slots for connected standby scenarios (just mention, too much detail).
Should be demo’d (and updated)
Better demo’d. Note the new alarms app for Win8.1
Background tasks get limited resources. Compare with Win32 services and stress battery life. Quotas do not roll over and get replenished at next refresh periodBackground tasks will be suspended if you run out of CPU timeThere are also network quota that depend on the energy cost per byte (slow energy hungry network connections get less time and throughput) There are global pools for network and CPU. Not guaranteed since they are shared. For Communication appsThis is not for control channel triggers, so your app will always be reachable.
Just like triggering Suspend and Resume you can trigger background tasks.
Just like triggering Suspend and Resume you can trigger background tasks. Better demo’d
Use the SDK sample: Background task sample. Change the time zone (first scenario). Fire the Trigger through Visual Studio IDEYou can snap the sample and fill with control panel to change time zone
Connected standby is on new devicesVery low power mode: Only <5% power consumptionNICs are still connected. Devices are SoC devices (ARM or x86)
@ 36:53Connected standby is on new devicesVery low power mode: Only <5% power consumptionNICs are still connected; timer still fires
Hanging background tasks is a major cause for crashes (yes crashes) on Surface. Developers make BGT long running and this prevents systems to go into standby. A system provided watchdog process will detect a task as being idle and then first cancel, then kill it, thereby creating a crash dump. Conclusion: keep the task short. No loops, time-out on network connections, etc.