Oliver Scheer
Senior Technical Evangelist
Microsoft Deutschland
http://the-oliver.com
Application
Lifecycle
• Windows Phone 8 program lifecycle
• Launching and Closing
• Deactivating and Activating
• Dormant and Tombstoned applica...
Windows Phone Program
Lifecycle
Tombstoned
• Windows Phone apps transition between different
application states
• Apps are launched from Start Screen icon...
Application Lifecycle Events
• The Windows Phone application environment notifies an application about lifecycle events
th...
Demo 1: Launching
and Closing
Launching and Closing – what we have seen
• When a Windows Phone 8 application is started the
Application_Launching event ...
Application Deactivation and Reactivation
• If you are from a Windows desktop background this behavior will make perfect s...
Demo 2: Deactivating
and Activating
Dormant applications
• The user can make your application dormant at any time
• They could launch another program from the...
Dormant applications
• The user can make your application dormant at any time
• They could launch another program from the...
Dealing with Dormant
• When your application is made dormant it must do as much data persistence as if it was
being closed...
Reactivating from Dormant
ActiveDormant
Resuming an Application – Fast Application Switching
• The user can resume a suspended application by
‘unwinding’ the appl...
From Dormant to Tombstoned
• An application will be held dormant in memory alongside other
applications
• If the operating...
Reactivating from Tombstoned
ActiveDormantTombstoned
Resumed from Dormant or Tombstoned?
• You can also check a flag to see if a the application is being resumed from dormant ...
Debugging Tombstoning
• You can force an application to be “tombstoned”
(removed from memory) when it is made
dormant by s...
Demo 3: Dormant vs
Tombstoned
States and Tombstones
• When an application is resumed from Dormant, it resumes exactly where it left off
• All objects an...
The Application State dictionary
• Transient data for a tombstoned application may be stored in the application state
dict...
Saving Transient Data on Deactivation
• Use the Page State dictionary to store transient data at page scope such as data t...
Restoring Transient Data on Reactivation
• In OnNavigatedTo, if the State dictionary contains the value stored by OnNaviga...
Demo 4: Using State
Dictionaries
Running Under Lock
Screen on Windows
Phone
Windows Phone Idle Detection
• The Windows Phone operating system will detect when an application is idle
• When the phone...
Windows Phone Idle Detection
• The Windows Phone operating system will detect when an application is idle
• When the phone...
Disabling Idle Detection
• This statement disables idle detection mode for your application
• It will now continue running...
Detecting “Obscured” events
• Your application can connect to the Obscured event for the enclosing frame
• This will fire ...
Simulation Dashboard
• The Simulation Dashboard is one of the tools
supplied with Visual Studio 2012
• It lets you simulat...
Fast Application Resume
Fast Application Resume
• By default a fresh instance of your application is always launched when the user starts a
new co...
Demo 6: Fast
Application Resume
Enabling FAR in PropertiesWMAppManifest.xml
• This is how FAR is selected
• You have to edit the file by hand, there is no...
The Two Flavors of FAR
• Oddly, you enable FAR by registering your app as a “LocationTracking” app – whether or
not you ac...
Standard App Relaunch Behavior
ActiveDormant
‘True’ Background Location Tracking Behavior
ActiveDormant
Location
Tracking
FAR-enabled App Behavior
ActiveDormant
Location
Tracking
Sounds Great! So Why Don’t I Use FAR With All My Apps?
• You need to be very careful on protecting the user experience wit...
App List/Primary Tile Behavior of FAR-enabled Apps
• Similarly, the user expectation when launching an app from an applica...
Detecting Resume in a FAR-enabled App
• In a true Background Location Tracking app, when the app is sent to the background...
private void InitializePhoneApplication()
{
...
// Handle reset requests for clearing the backstack
RootFrame.Navigated +=...
private void InitializePhoneApplication()
{
...
// Handle reset requests for clearing the backstack
RootFrame.Navigated +=...
Review
• Programs can be Launched (from new) or Activated (from Dormant or Tombstoned)
• The operating system provides a s...
The information herein is for informational
purposes only an represents the current view of
Microsoft Corporation as of th...
Upcoming SlideShare
Loading in …5
×

Windows Phone 8 - 5 Application Lifecycle

1,613 views

Published on

Published in: Technology
1 Comment
0 Likes
Statistics
Notes
  • Be the first to like this

No Downloads
Views
Total views
1,613
On SlideShare
0
From Embeds
0
Number of Embeds
4
Actions
Shares
0
Downloads
34
Comments
1
Likes
0
Embeds 0
No embeds

No notes for slide

Windows Phone 8 - 5 Application Lifecycle

  1. 1. Oliver Scheer Senior Technical Evangelist Microsoft Deutschland http://the-oliver.com Application Lifecycle
  2. 2. • Windows Phone 8 program lifecycle • Launching and Closing • Deactivating and Activating • Dormant and Tombstoned applications • Simulation Dashboard • Idle Detection on Windows Phone • Detecting Obscured events • Fast Application Resume Agenda In This Session… 3/18/20142 • Lifecycle design • Page Navigation and the Back Stack
  3. 3. Windows Phone Program Lifecycle
  4. 4. Tombstoned • Windows Phone apps transition between different application states • Apps are launched from Start Screen icon, apps menu or from deep link • User may close apps • The OS will suspend your app if it loses focus Suspended apps may be tombstoned • Apps may be reactivated from a suspended state • When the user starts a new instance of your app, any suspended instance is discarded • In Windows Phone 8.0, you can enable Fast Application Resume to relaunch the suspended instance Windows Phone Application Lifecycle 3/18/2014 Not running Running LaunchingClosing DeactivatingActivating Dormant
  5. 5. Application Lifecycle Events • The Windows Phone application environment notifies an application about lifecycle events through a set of events • In the project templates, the events are already wired up in App.xaml and the event handler methods are in the App.xaml.cs file • Initially the event handler methods are empty // Code to execute when the application is launching (eg, from Start) // This code will not execute when the application is reactivated private void Application_Launching(object sender, LaunchingEventArgs e) { }
  6. 6. Demo 1: Launching and Closing
  7. 7. Launching and Closing – what we have seen • When a Windows Phone 8 application is started the Application_Launching event handler method is called • Good place to load content from backing store • When a Windows Phone 8 application is ended the Application_Closing event handler method is called • Good place to save content in backing store • The debugger will keep running even when your application is “stopped” • This makes it easier to debug start and stop behaviour • But you need to stop it yourself to work on your code.. 3/18/2014 Not running Running Application_ Launching Application_ Closing
  8. 8. Application Deactivation and Reactivation • If you are from a Windows desktop background this behavior will make perfect sense • Windows desktop applications can subscribe to events that are fired when the program starts and ends • However, Windows Phone applications operate on a smartphone and the OS imposes restrictions designed to save battery life and ensure a good end-user experience • At any give time only one applications is in the foreground • Users may deactivate their applications and reactivate them later • Applications have to deal with being activated and deactivated 3/18/20148
  9. 9. Demo 2: Deactivating and Activating
  10. 10. Dormant applications • The user can make your application dormant at any time • They could launch another program from the start screen or the Programs menu • The Application_Deactivated method is called in this situation • External events may also make your application dormant • If a phone call is received when your program is running it will be made dormant • If the lock screen shows after a period of inactivity • A user may return to your application and resume it at a later time 3/18/2014 Tombstoned Running DeactivatingActivating Dormant
  11. 11. Dormant applications • The user can make your application dormant at any time • They could launch another program from the start screen or the Programs menu • The Application_Deactivated method is called in this situation • External events may also make your application dormant • If a phone call is received when your program is running it will be made dormant • If the lock screen shows after a period of inactivity • A user may return to your application and resume it at a later time 3/18/2014 Tombstoned Running DeactivatingActivating Dormant There is no guarantee that your application will ever be resumed if it is made dormant
  12. 12. Dealing with Dormant • When your application is made dormant it must do as much data persistence as if it was being closed • Because Application_Deactivated and Application_Closing will mean the same thing if the user never comes back to your program • Your application can run for up to 5 seconds to perform this tidying up • After that it will be forcibly removed from memory • When an application is resumed from dormant it will automatically resume at the page where it was deactivated • This behaviour is managed by the operating system • All objects are still in memory exactly as they were at the moment the app was suspended 3/18/201412
  13. 13. Reactivating from Dormant ActiveDormant
  14. 14. Resuming an Application – Fast Application Switching • The user can resume a suspended application by ‘unwinding’ the application history stack by continually pressing the ‘Back’ key to close applications higher up the history stack, until the suspended application is reached • The Back button also has a “long press” behaviour • This allows the user to select the active application from the stack of interrupted ones • Screenshots of all the applications in the stack are displayed and the user can select the one that they want • The application is brought directly into the foreground if it is selected by the user • On Windows Phone 8, the app history stack can hold up to 8 applications 14
  15. 15. From Dormant to Tombstoned • An application will be held dormant in memory alongside other applications • If the operating system becomes short of memory it will discard the cached state of the oldest dormant application • This process is called “Tombstoning” • The page navigation history and a special cache called the state dictionaries are maintained for a tombstoned application • When a dormant application is resumed the application resumes running just where it left off • When a tombstoned application is resumed, it restarts at the correct page but all application state has been lost – you must reload it • An application can determine which state it is being activated from 3/18/201415 Tombstoned Running DeactivatingActivating Dormant
  16. 16. Reactivating from Tombstoned ActiveDormantTombstoned
  17. 17. Resumed from Dormant or Tombstoned? • You can also check a flag to see if a the application is being resumed from dormant or tombstoned state private void Application_Activated(object sender, ActivatedEventArgs e) { if (e.IsApplicationInstancePreserved) { // Dormant - objects in memory intact } else { // Tombstoned - need to reload } }
  18. 18. Debugging Tombstoning • You can force an application to be “tombstoned” (removed from memory) when it is made dormant by setting this in Visual Studio • You should do this as part of your testing regime • You can also use the Simulation Dashboard to show the lock screen on the emulator which will also cause your application to be made dormant 3/18/201418
  19. 19. Demo 3: Dormant vs Tombstoned
  20. 20. States and Tombstones • When an application is resumed from Dormant, it resumes exactly where it left off • All objects and their state is still in memory • You may need to run some logic to reset time-dependent code or networking calls • When an application is resumed from Tombstoned, it resumes on the same page where it left off but all in-memory objects and the state of controls has been lost • Persistent data will have been restored, but what about transient data or “work in progress” at the time the app was suspended? • This is what the state dictionaries are for, to store transient data • State dictionaries are held by the system for suspended applications • When a new instance of an application is launched the state dictionaries are empty • If there is a previous instance of the application that is suspended, standard behaviour is that the suspended instance – along with its state dictionaries - is discarded 3/18/201420
  21. 21. The Application State dictionary • Transient data for a tombstoned application may be stored in the application state dictionary • This can be set in the Application_Deactivated method and then restored to memory when the application is activated from tombstoned • This means that the Application_Deactivated method has two things to do: • Store persistent data in case the application is never activated again • Optionally store transient data in the application state dictionary in case the user comes back to the application from a tombstoned state PhoneApplicationService.Current.State["Url"] = "www.robmiles.com";
  22. 22. Saving Transient Data on Deactivation • Use the Page State dictionary to store transient data at page scope such as data the user has entered but not saved yet • Page and Application State are string-value dictionaries held in memory by the system but which is not retained over reboots protected override void OnNavigatedFrom(System.Windows.Navigation.NavigationEventArgs e) { base.OnNavigatedFrom(e); if (e.NavigationMode != System.Windows.Navigation.NavigationMode.Back && e.NavigationMode != System.Windows.Navigation.NavigationMode.Forward) { // If we are exiting the page because we've navigated back or forward, // no need to save transient data, because this page is complete. // Otherwise, we're being deactivated, so save transient data // in case we get tombstoned this.State["incompleteEntry"] = this.logTextBox.Text; } }
  23. 23. Restoring Transient Data on Reactivation • In OnNavigatedTo, if the State dictionary contains the value stored by OnNavigatedFrom, then you know that the page is displaying because the application is being reactivated protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e) { base.OnNavigatedTo(e); // If the State dictionary contains our transient data, // we're being reactivated so restore the transient data if (this.State.ContainsKey("incompleteEntry")) { this.logTextBox.Text = (string)this.State["incompleteEntry"]; } }
  24. 24. Demo 4: Using State Dictionaries
  25. 25. Running Under Lock Screen on Windows Phone
  26. 26. Windows Phone Idle Detection • The Windows Phone operating system will detect when an application is idle • When the phone enters idle state the lock screen is engaged • The user can configure the timeout value, or even turn it off • When an application is determined to be idle it will be Deactivated and then Activated when the user unlocks the phone again • An application disable this behaviour, so that it is able to run underneath the lock screen 3/18/201426
  27. 27. Windows Phone Idle Detection • The Windows Phone operating system will detect when an application is idle • When the phone enters idle state the lock screen is engaged • The user can configure the timeout value, or even turn it off • When an application is determined to be idle it will be Deactivated and then Activated when the user unlocks the phone again • An application disable this behaviour, so that it is able to run underneath the lock screen This is strong magic. It gives you the means to create a “battery flattener” which users will hate. Use it with care, read the guidance in the documentation and follow the checklists. 3/18/201427
  28. 28. Disabling Idle Detection • This statement disables idle detection mode for your application • It will now continue running under the lock screen • There will be no Activated or Deactivated messages when the phone locks because the application is timed out • Note that your application will still be deactivated if the users presses the Start button • Disabling idle detection is not a way that you can run two applications at once PhoneApplicationService.Current.ApplicationIdleDetectionMode = IdleDetectionMode.Disabled;
  29. 29. Detecting “Obscured” events • Your application can connect to the Obscured event for the enclosing frame • This will fire if something happens (Toast message, Lock Screen, Incoming call) that will obscure your frame • It also fires when the obscuring item is removed • You can use the ObscuredEventArgs value to detect the context of the call App.RootFrame.Obscured += RootFrame_Obscured; ... void RootFrame_Obscured(object sender, ObscuredEventArgs e) { }
  30. 30. Simulation Dashboard • The Simulation Dashboard is one of the tools supplied with Visual Studio 2012 • It lets you simulate the environment of your application • It also lets you lock and unlock the screen of the emulator phone • This will cause Deactivated and Activated events to fire in your program 3/18/201430
  31. 31. Fast Application Resume
  32. 32. Fast Application Resume • By default a fresh instance of your application is always launched when the user starts a new copy from the programs page or a deep link in a secondary tile or reminder, or via new features such as File and Protocol associations or launching by speech commands • This forces all the classes and data to be reloaded and slows down activation • Windows Phone 8 provides Fast Application Resume, which reactivates a dormant application if the user launches a new copy • This feature was added to enable background location tracking • You can take advantage of it to reactivate a dormant application instead of launching a new instance 3/18/201441
  33. 33. Demo 6: Fast Application Resume
  34. 34. Enabling FAR in PropertiesWMAppManifest.xml • This is how FAR is selected • You have to edit the file by hand, there is no GUI for this <Tasks> <DefaultTask Name ="_default" NavigationPage="MainPage.xaml"/> </Tasks> <Tasks> <DefaultTask Name ="_default" NavigationPage="MainPage.xaml"> <BackgroundExecution> <ExecutionType Name="LocationTracking" /> </BackgroundExecution> </DefaultTask> </Tasks>
  35. 35. The Two Flavors of FAR • Oddly, you enable FAR by registering your app as a “LocationTracking” app – whether or not you actually track location! • If you have marked your app LocationTracking *and* you actively track location by using the GeoCoordinateWatcher or GeoLocator classes: • App continues to run in the background if it is deactivated while actively tracking • If re-launched from the Apps menu or via a Deep Link, the existing instance will be reactivated if it is running in the background or fast resumed if it is dormant • More on this in the Maps and Location Session! • If you have marked your app LocationTracking but you don’t have any Geolocation code in your app, then your app is one that can be fast resumed • When deactivated, your app is suspended just like normal • But when your app is relaunched and the previous instance is currently dormant, that previous instance is fast resumed 3/18/201444
  36. 36. Standard App Relaunch Behavior ActiveDormant
  37. 37. ‘True’ Background Location Tracking Behavior ActiveDormant Location Tracking
  38. 38. FAR-enabled App Behavior ActiveDormant Location Tracking
  39. 39. Sounds Great! So Why Don’t I Use FAR With All My Apps? • You need to be very careful on protecting the user experience with respect to page navigation • Deep Link activation • On non FAR-enabled apps, if you launch an app to ‘Page2’, then ‘Page2’ is the only page in the page backstack, and pressing Back closes the app • For FAR-enabled apps, if you launch an app to ‘Page2’, but there was a suspended instance containing a page history backstack of ‘MainPage’, ‘Page1’, ‘Page2’, ‘Page3’ then the newly launched app will end up with a backstack of ‘MainPage’, ‘Page1’, ‘Page2’, ‘Page3’, ‘Page2’ • What should the user experience be here? 3/18/201448
  40. 40. App List/Primary Tile Behavior of FAR-enabled Apps • Similarly, the user expectation when launching an app from an application tile on the Start Screen or from the Apps List is that the app will launch at the home page of the app • This is what will happen for non FAR-enabled apps • This is what will happen even for FAR-enabled apps if there is no suspended instance at the time the app is launched • Since your app can now resume, what should the user experience be? • Should you always launch on the home page to match previous behaviour of Windows Phone apps? • Or should you resume at the page the user was last on? • If you resume at the last page the user was on, think about how the user will navigate to the home page; good idea to put a home icon on the app bar of the page the user lands on 3/18/201449
  41. 41. Detecting Resume in a FAR-enabled App • In a true Background Location Tracking app, when the app is sent to the background it continues to run • App will get PhoneApplicationService.RunningInBackground event instead of the Application_Deactivated event • When an app enabled for Fast App Resume (aka FAR) is relaunched from the App List or a Deep Link: • Page on the top of the backstack gets navigated with NavigationMode.Reset • Next, the page in the new launch url will be navigated to with NavigationMode.New • You can decide whether to unload the page backstack or not, or maybe cancel the navigation to the new page 3/18/201450
  42. 42. private void InitializePhoneApplication() { ... // Handle reset requests for clearing the backstack RootFrame.Navigated += CheckForResetNavigation; ... } private void CheckForResetNavigation(object sender, NavigationEventArgs e) { // If the app has received a 'reset' navigation, then we need to check // on the next navigation to see if the page stack should be reset if (e.NavigationMode == NavigationMode.Reset) RootFrame.Navigated += ClearBackStackAfterReset; } Clearing Previously Launched Pages on Fast App Resume Add Logic to App.Xaml.cs to Check for Reset Navigation (Behavior Already Implemented in Project Templates) 3/18/2014Microsoft confidential51
  43. 43. private void InitializePhoneApplication() { ... // Handle reset requests for clearing the backstack RootFrame.Navigated += CheckForResetNavigation; ... } private void CheckForResetNavigation(object sender, NavigationEventArgs e) { // If the app has received a 'reset' navigation, then we need to check // on the next navigation to see if the page stack should be reset if (e.NavigationMode == NavigationMode.Reset) RootFrame.Navigated += ClearBackStackAfterReset; } private void ClearBackStackAfterReset(object sender, NavigationEventArgs e) Clearing Previously Launched Pages on Fast App Resume Add Logic to App.Xaml.cs to Check for Reset Navigation (Behavior Already Implemented in Project Templates) 3/18/2014Microsoft confidential52
  44. 44. Review • Programs can be Launched (from new) or Activated (from Dormant or Tombstoned) • The operating system provides a state storage object and navigates to the correct page when activating an application that has been running, but you have to repopulate forms • Programs can run behind the Lock Screen by disabling Idle Timeout – but this is potentially dangerous (and apps must deal with the Obscured event in this situation) • The system maintains a Back Stack for application navigation. This must be managed to present the best user experience when applications are started in different ways • Applications are normally launched anew each time they are started from the Programs page, but it is now possible to restart a suspended instance using Fast Application Resume • YOU MUST PLAN YOUR LAUNCHING AND BACK STACK BEHAVIOUR FROM THE START 3/18/201453
  45. 45. The information herein is for informational purposes only an 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. © 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. MICROSOFT MAKES NO WARRANTIES, EXPRESS, IMPLIED OR STATUTORY, AS TO THE INFORMATION IN THIS PRESENTATION.

×