windows phone fast app switching, tombstoning and multitasking
DESCRIPTION
More info on http://www.techdays.beTRANSCRIPT
Windows Phone Fast App Switching, Tombstoning and Multitasking
Ben RigaTechnical EvangelistWindows Phone
[email protected]@benriga
Follow me on Twitter
or the Puppy gets it@benriga
Topics• Fast Application Switching• The Windows Phone execution model• Application State Management• Fast Application Switching• Dormant programs and Tombstoning• Application Navigation and Application Switching
• Background Tasks• Generic Agents• Background Transfer Service• Alarms and Reminders
DemoFast ApplicationSwitching
Application Lifecycle - Dormant
running
deactivated
dormant
activated
Phone resources detachedThreads & timers suspended
Fast App Resume
Save State!State preserved!e.IsApplicationInstancePreserved== true
Application Lifecycle - Tombstoned
running
deactivated
dormant Phone resources detachedThreads & timers suspended
Restore state!e.IsApplicationInstancePreserved == false
Resuming .. .
Tombstone the oldest app
tombstoned
activated
Methods & Events
7
Finding the Resume type
The Activation handler can test a flag to determine the type of resume taking place
private void Application_Activated(object sender, ActivatedEventArgs e){ if (e.IsApplicationInstancePreserved) { // Dormant - objects in memory intact } else { // Tombstoned - need to reload }}
Deactivation Resource ManagementDeactivated App
PhoneApplicationPage.OnNavigatedFrom
PhoneApplicationService.Deactivated
Framework:Detach Resources
Framework:Suspend Timers and Threads
Dormant App
MediaPlayer.PauseMediaElement.Pause
SoundEffectInstance.PauseVibrateController.StopPhotoCamera.Dispose
Save page/global state
XNA Audio Paused
Sensors Notifications suppressed
Networking Cancelled
Sockets Disconnected
MediaElement Disconnected
Camera Disposed
Activation Resource Management
MediaElement.Source/Position/PlaySocket.ConnectAsyncnew PhotoCamera/VideoCamera
Restore app state if tombstoned
Running App
PhoneApplicationPage.OnNavigatedTo
PhoneApplicationService.Activated
Framework:Attach Resources
Framework:Resume Timers and Threads
Dormant App
XNA Audio Resumed
Sensors Notifications resumed
Networking Completed with Cancellation
Sockets -
MediaElement -
Camera -
Isolated Storage vs State Storage• Isolated storage is so called because the data for an
application is isolated from all other applications • It can be used as filestore where an application can store folders
and files• It is slow to access, since it is based on NVRAM technology• It can also be used to store name/value pairs, e.g. program settings
• State storage is so called because it is used to hold the state of an application• It can be used to store name/value pairs which are held in memory
for dormant or tombstoned applications• It provides very quick access to data
11
DemoCaptain’s LogWith No StorageWith StorageFully Working
Fast App Switching and Tombstoning Review• Only one Windows Phone application is Active at any time• The Start and Back buttons on the phone are used to
start new applications and return to previously used ones• If an application is replaced by another it is either made
Dormant (still in memory but not running) or Tombstoned (removed from memory)
• Applications must use populate methods provided in the App.xaml.cs class to save and retrieve state information when appropriate• State can be stored in memory for quick reload and in isolated
storage which serve as a permanent store
Background Tasks
Multitasking Capabilities• Background Agents• Periodic• Resource Intensive
• Background Transfer Service• Alarms and Reminders• Background Audio
Background Agents• Agents• Periodic• Resource Intensive
• An app may have up to one of each • Initialized in foreground, run in background• Persisted across reboots
• User control through CPL• System maximum of 18 periodic agent
• Agent runs for up to 14 days (can be renewed)
Generic Agent TypesPeriodic Agents• Occurrence• Every 30 min
• Duration• ~15 seconds
• Constraints• <= 6 MB Memory• <=10% CPU
Resource Intensive Agents• Occurrence• External power• Non-cell network
• Duration• 10 minutes
• Constraints • <= 6 MB Memory
Background Agent Functionality
Allowed
Tiles Toast Location Network R/W ISO store Sockets Most framework APIs
Restricted
Display UI XNA libraries Microphone and Camera Sensors Play audio
(may only use background audio APIs)
DemoCaptain’s Location Log
Debugging a Background Task
• It would be annoying if we had to wait 30 minutes to get code in the agent running so we could debug it
• When we are debugging we can force service to launch itself
• Such code can be conditionally compiled and removed before the production version is built
#if DEBUG_AGENT ScheduledActionService.LaunchForTest(taskName,
TimeSpan.FromSeconds(60));#endif
Debugging the Agent Code• When you use the Back button or Start on the phone to interrupt
an application with an active Background Task ,Visual Studio does not stop running
• It remains attached to the application• You can then put breakpoints into the background task
application and debug them as you would any other program• You can single step, view the contents of variables and even
change them using the Immediate Window• This is also true if you are working on a device rather than the
emulator• The same techniques work on ResourceIntensiveAgents
DemoDebugging Tasks
File Transfer Tasks• It is also possible to create a background task to transfer
files to and from your application’s isolated storage• The transfers will continue to work even when the
application is not running• An application can monitor the state of the downloads and
display their status• Files can be fetched from HTTP or HTTPs hosts• At the moment FTP is not supported
• The system maintains a queue of active transfers and services each one in turn
• Applications can query the state of active transfers
Background Transfer Policies• There are a set of policies that control transfer
behaviour• Maximum Upload file size: 5Mb• Maximum Download file size over cellular (mobile phone)
data: 20Mb• Maximum Download file size over WiFi: 100Mb
• These can be modified by setting the value of TransferPreferences on a particular transfer
Transfer Management• An application can find out how many file transfers
it has active• It will have to do this when it is restarted, as file transfers
will continue even when the application is not running• It can then perform transfer management as
required• There is a good example of transfer list
management on MSDN:
• http://msdn.microsoft.com/en-us/library/hh202953.aspx
DemoPicture Fetch
Scheduled Notifications• Time-based, on-phone notifications• Supports Alerts & Reminders• Persist across reboots• Adheres to user settings• Consistent with phone UX
Alarms vs Reminders? Alarms Reminders
• Modal• Snooze and
Dismiss• Sound
customization• No app
invocation• No stacking
• Rich information• Integrates with
other reminders• Snooze and
Dismiss• Launch app• Follows the
phones global settings
Creating a Reminder
• This code creates a reminder and adds it as a scheduled service
• The value eggTime holds the length of the delay• This code also sets the url of the page in the application
using Microsoft.Phone.Scheduler;...eggReminder = new Reminder("Egg Timer");
eggReminder.BeginTime = DateTime.Now + new TimeSpan(0, eggTime, 0);eggReminder.Content = "Egg Ready";eggReminder.RecurrenceType = RecurrenceInterval.None;eggReminder.NavigationUri = new Uri("/EggReadyPage.xaml",
UriKind.Relative);
ScheduledActionService.Add(eggReminder);
Reminder Housekeeping
• Reminders are identified by name• This code finds the “Egg Timer” reminder and then
removes it from the scheduler
Reminder eggReminder = ScheduledActionService.Find("Egg Timer") as Reminder;
if ( eggReminder != null ) { ScheduledActionService.Remove("Egg Timer");}
DemoDemo4: Egg Timer
Audio Playback Agents• It is also possible to
create an Audio Playback Agent that will manage an application controlled playlist
• The mechanism is the same as for other background tasks
• The audio can be streamed or held in the application isolated storage
Background Audio• Playback• App provides URL or stream to Zune• Audio continues to play even if app is closed• App is notified of file or buffer near completion
• Phone Integration• Music & Video Hub• Universal Volume Control (UVC), lauch app, controls, contextual info• Contextual launch – Start menu, UVC, Music & Video Hub
• App Integration• App can retrieve playback status, progress, & metadata• Playback notification registration
Review• An application can create background processes• Periodic Task and ResourceIntensive task run when the application is
stopped• Scheduled notifications will fire whether the application is running
or not• Audio Playback run alongside the application
• Applications and their background processes can communicate via isolated storage
• Visual Studio can be used to debug background tasks in the same way as foreground applications
Be what’s next: Windows Phone• Find everything here
http://aka.ms/mbl-phone/start • Download your free Windows Phone Dev Tools
http://aka.ms/mbl-phone/tools• Channel9 ‘Get to Mango’ series
http://aka.ms/mbl-phone/mango• Register as a developer
http://aka.ms/mbl-phone/register
Follow me on Twitter
or the Puppy gets it@benriga
Q&A Ben RigaTechnical EvangelistWindows Phone
[email protected]@benriga
© 2012 Microsoft Corporation. All rights reserved. Microsoft, Windows, Windows Vista and other product names are or may be registered trademarks and/or trademarks in the U.S. and/or other countries.The information herein is for informational purposes only and represents the current view of Microsoft Corporation as of the date of this presentation. Because Microsoft must respond to changing market conditions, it should not be interpreted to be a commitment on the part of Microsoft, and Microsoft cannot guarantee the accuracy of any information provided after the date of this presentation. MICROSOFT MAKES NO WARRANTIES, EXPRESS, IMPLIED OR STATUTORY, AS TO THE INFORMATION IN THIS PRESENTATION.