SlideShare a Scribd company logo
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 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
Windows Phone Program
Lifecycle
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
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)
{
}
Demo 1: Launching
and Closing
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
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
Demo 2: Deactivating
and Activating
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
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
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
Reactivating from Dormant
ActiveDormant
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
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
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 or
tombstoned state
private void Application_Activated(object sender, ActivatedEventArgs e)
{
if (e.IsApplicationInstancePreserved)
{
// Dormant - objects in memory intact
}
else
{
// Tombstoned - need to reload
}
}
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
Demo 3: Dormant vs
Tombstoned
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
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";
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;
}
}
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"];
}
}
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 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
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
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;
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)
{
}
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
Fast Application Resume
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
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 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>
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
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 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
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
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
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
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
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
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.

More Related Content

PPTX
Hypervisor
kalpita surve
 
PPT
An Introduction To Server Virtualisation
Alan McSweeney
 
PDF
Android resources
ma-polimi
 
PDF
Lecture5 virtualization
hktripathy
 
PPS
Java Exception handling
kamal kotecha
 
PPT
Virtualization in cloud
Ashok Kumar
 
PDF
Hcx intro preso v2
Parashar Singh
 
PPTX
Jdbc ppt
sandeep54552
 
Hypervisor
kalpita surve
 
An Introduction To Server Virtualisation
Alan McSweeney
 
Android resources
ma-polimi
 
Lecture5 virtualization
hktripathy
 
Java Exception handling
kamal kotecha
 
Virtualization in cloud
Ashok Kumar
 
Hcx intro preso v2
Parashar Singh
 
Jdbc ppt
sandeep54552
 

What's hot (20)

PPTX
Module1 elementary concepts of objects and classes
MersonSir
 
PPT
VMware Esx Short Presentation
Barcamp Cork
 
PPTX
VMware vSphere technical presentation
aleyeldean
 
PPTX
virtualization and hypervisors
Gaurav Suri
 
PDF
Hypervisors
SrikantMishra12
 
PDF
The dark side of stretched cluster
Andrea Mauro
 
PPTX
Virtualization concept slideshare
Yogesh Kumar
 
PPTX
Android - Application Framework
Yong Heui Cho
 
PPT
VMware Presentation
Emirates Computers
 
PDF
malloc & vmalloc in Linux
Adrian Huang
 
PPTX
Interface in java
PhD Research Scholar
 
PPTX
Virtualization- Cloud Computing
NIKHILKUMAR SHARDOOR
 
PDF
Android graphics
Krazy Koder
 
PPTX
Spring framework IOC and Dependency Injection
Anuj Singh Rajput
 
PPT
EJB .
ayyagari.vinay
 
PPTX
Advance Java Topics (J2EE)
slire
 
PPTX
Android graphic system (SurfaceFlinger) : Design Pattern's perspective
Bin Chen
 
PPTX
Interfaces in java
Abishek Purushothaman
 
PPTX
VMware Overview
Madhu Bala
 
Module1 elementary concepts of objects and classes
MersonSir
 
VMware Esx Short Presentation
Barcamp Cork
 
VMware vSphere technical presentation
aleyeldean
 
virtualization and hypervisors
Gaurav Suri
 
Hypervisors
SrikantMishra12
 
The dark side of stretched cluster
Andrea Mauro
 
Virtualization concept slideshare
Yogesh Kumar
 
Android - Application Framework
Yong Heui Cho
 
VMware Presentation
Emirates Computers
 
malloc & vmalloc in Linux
Adrian Huang
 
Interface in java
PhD Research Scholar
 
Virtualization- Cloud Computing
NIKHILKUMAR SHARDOOR
 
Android graphics
Krazy Koder
 
Spring framework IOC and Dependency Injection
Anuj Singh Rajput
 
Advance Java Topics (J2EE)
slire
 
Android graphic system (SurfaceFlinger) : Design Pattern's perspective
Bin Chen
 
Interfaces in java
Abishek Purushothaman
 
VMware Overview
Madhu Bala
 
Ad

Similar to Windows Phone 8 - 5 Application Lifecycle (20)

PDF
Windows phone 8 session 9
hitesh chothani
 
PDF
Windows Phone 8 Fundamental
Nguyên Phạm
 
PDF
follow-app BOOTCAMP 2: Windows phone fast application switching
QIRIS
 
PPTX
07 wp7 application lifecycle
Tao Wang
 
PPTX
Cool Stuff Your App Can Do
Ed Donahue
 
PDF
Bcsf13a019_mcqs_ead
MarYam IqBal
 
PPTX
What's new in Windows Phone Mango for Developers
Glen Gordon
 
PPTX
An end-to-end experience of Windows Phone 7 development (Part 1)
rudigrobler
 
PPTX
Windows Phone Fast App Switching, Tombstoning and Multitasking
Microsoft Developer Network (MSDN) - Belgium and Luxembourg
 
PDF
Windows phone 7 series
openbala
 
PPTX
Ciclo di vita di una applicazione windows phone tips & tricks
Dan Ardelean
 
PPTX
Windows 8 BootCamp
Einar Ingebrigtsen
 
PPTX
07 windows runtime app lifecycle
WindowsPhoneRocks
 
PPTX
Designing for Windows Phone 8
David Isbitski
 
PPTX
Windows Phone Application Platform
Dave Bost
 
PPTX
Windows 8 Client Part 2 "The Application internals for IT-Pro's"
Microsoft TechNet - Belgium and Luxembourg
 
PPTX
23 silverlight apps on windows phone 8.1
WindowsPhoneRocks
 
PPTX
Windows Phone 7.5 Mango - What's New
Sascha Corti
 
PPTX
Sinergija 12 Windows Phone is around the corned
Catalin Gheorghiu
 
PPTX
Windows phone7 subodh
Subodh Pushpak
 
Windows phone 8 session 9
hitesh chothani
 
Windows Phone 8 Fundamental
Nguyên Phạm
 
follow-app BOOTCAMP 2: Windows phone fast application switching
QIRIS
 
07 wp7 application lifecycle
Tao Wang
 
Cool Stuff Your App Can Do
Ed Donahue
 
Bcsf13a019_mcqs_ead
MarYam IqBal
 
What's new in Windows Phone Mango for Developers
Glen Gordon
 
An end-to-end experience of Windows Phone 7 development (Part 1)
rudigrobler
 
Windows Phone Fast App Switching, Tombstoning and Multitasking
Microsoft Developer Network (MSDN) - Belgium and Luxembourg
 
Windows phone 7 series
openbala
 
Ciclo di vita di una applicazione windows phone tips & tricks
Dan Ardelean
 
Windows 8 BootCamp
Einar Ingebrigtsen
 
07 windows runtime app lifecycle
WindowsPhoneRocks
 
Designing for Windows Phone 8
David Isbitski
 
Windows Phone Application Platform
Dave Bost
 
Windows 8 Client Part 2 "The Application internals for IT-Pro's"
Microsoft TechNet - Belgium and Luxembourg
 
23 silverlight apps on windows phone 8.1
WindowsPhoneRocks
 
Windows Phone 7.5 Mango - What's New
Sascha Corti
 
Sinergija 12 Windows Phone is around the corned
Catalin Gheorghiu
 
Windows phone7 subodh
Subodh Pushpak
 
Ad

More from Oliver Scheer (18)

PPTX
Windows Phone 8 - 17 The Windows Phone Store
Oliver Scheer
 
PPTX
Windows Phone 8 - 16 Wallet and In-app Purchase
Oliver Scheer
 
PPTX
Windows Phone 8 - 15 Location and Maps
Oliver Scheer
 
PPTX
Windows Phone 8 - 14 Using Speech
Oliver Scheer
 
PPTX
Windows Phone 8 - 13 Near Field Communcations and Bluetooth
Oliver Scheer
 
PPTX
Windows Phone 8 - 12 Network Communication
Oliver Scheer
 
PPTX
Windows Phone 8 - 11 App to App Communication
Oliver Scheer
 
PPTX
Windows Phone 8 - 10 Using Phone Resources
Oliver Scheer
 
PPTX
Windows Phone 8 - 9 Push Notifications
Oliver Scheer
 
PPTX
Windows Phone 8 - 8 Tiles and Lock Screen Notifications
Oliver Scheer
 
PPTX
Windows Phone 8 - 7 Local Database
Oliver Scheer
 
PPTX
Windows Phone 8 - 6 Background Agents
Oliver Scheer
 
PPTX
Windows Phone 8 - 4 Files and Storage
Oliver Scheer
 
PPTX
Windows Phone 8 - 3.5 Async Programming
Oliver Scheer
 
PPTX
Windows Phone 8 - 1 Introducing Windows Phone 8 Development
Oliver Scheer
 
PPTX
Windows Phone 8 - 3 Building WP8 Applications
Oliver Scheer
 
PPTX
Windows Phone 8 - 4 Files and Storage
Oliver Scheer
 
PPTX
Windows Phone 8 - 2 Designing WP8 Applications
Oliver Scheer
 
Windows Phone 8 - 17 The Windows Phone Store
Oliver Scheer
 
Windows Phone 8 - 16 Wallet and In-app Purchase
Oliver Scheer
 
Windows Phone 8 - 15 Location and Maps
Oliver Scheer
 
Windows Phone 8 - 14 Using Speech
Oliver Scheer
 
Windows Phone 8 - 13 Near Field Communcations and Bluetooth
Oliver Scheer
 
Windows Phone 8 - 12 Network Communication
Oliver Scheer
 
Windows Phone 8 - 11 App to App Communication
Oliver Scheer
 
Windows Phone 8 - 10 Using Phone Resources
Oliver Scheer
 
Windows Phone 8 - 9 Push Notifications
Oliver Scheer
 
Windows Phone 8 - 8 Tiles and Lock Screen Notifications
Oliver Scheer
 
Windows Phone 8 - 7 Local Database
Oliver Scheer
 
Windows Phone 8 - 6 Background Agents
Oliver Scheer
 
Windows Phone 8 - 4 Files and Storage
Oliver Scheer
 
Windows Phone 8 - 3.5 Async Programming
Oliver Scheer
 
Windows Phone 8 - 1 Introducing Windows Phone 8 Development
Oliver Scheer
 
Windows Phone 8 - 3 Building WP8 Applications
Oliver Scheer
 
Windows Phone 8 - 4 Files and Storage
Oliver Scheer
 
Windows Phone 8 - 2 Designing WP8 Applications
Oliver Scheer
 

Recently uploaded (20)

PDF
Automating ArcGIS Content Discovery with FME: A Real World Use Case
Safe Software
 
PDF
The Future of Artificial Intelligence (AI)
Mukul
 
PDF
Brief History of Internet - Early Days of Internet
sutharharshit158
 
PDF
Security features in Dell, HP, and Lenovo PC systems: A research-based compar...
Principled Technologies
 
PPTX
Simple and concise overview about Quantum computing..pptx
mughal641
 
PDF
How ETL Control Logic Keeps Your Pipelines Safe and Reliable.pdf
Stryv Solutions Pvt. Ltd.
 
PDF
Economic Impact of Data Centres to the Malaysian Economy
flintglobalapac
 
PDF
OFFOFFBOX™ – A New Era for African Film | Startup Presentation
ambaicciwalkerbrian
 
PDF
Peak of Data & AI Encore - Real-Time Insights & Scalable Editing with ArcGIS
Safe Software
 
PDF
Trying to figure out MCP by actually building an app from scratch with open s...
Julien SIMON
 
PPTX
AI and Robotics for Human Well-being.pptx
JAYMIN SUTHAR
 
PDF
Make GenAI investments go further with the Dell AI Factory
Principled Technologies
 
PDF
Responsible AI and AI Ethics - By Sylvester Ebhonu
Sylvester Ebhonu
 
PDF
Orbitly Pitch Deck|A Mission-Driven Platform for Side Project Collaboration (...
zz41354899
 
PPTX
The-Ethical-Hackers-Imperative-Safeguarding-the-Digital-Frontier.pptx
sujalchauhan1305
 
PDF
GDG Cloud Munich - Intro - Luiz Carneiro - #BuildWithAI - July - Abdel.pdf
Luiz Carneiro
 
PPTX
New ThousandEyes Product Innovations: Cisco Live June 2025
ThousandEyes
 
PDF
Presentation about Hardware and Software in Computer
snehamodhawadiya
 
PDF
NewMind AI Weekly Chronicles - July'25 - Week IV
NewMind AI
 
PDF
CIFDAQ's Market Wrap : Bears Back in Control?
CIFDAQ
 
Automating ArcGIS Content Discovery with FME: A Real World Use Case
Safe Software
 
The Future of Artificial Intelligence (AI)
Mukul
 
Brief History of Internet - Early Days of Internet
sutharharshit158
 
Security features in Dell, HP, and Lenovo PC systems: A research-based compar...
Principled Technologies
 
Simple and concise overview about Quantum computing..pptx
mughal641
 
How ETL Control Logic Keeps Your Pipelines Safe and Reliable.pdf
Stryv Solutions Pvt. Ltd.
 
Economic Impact of Data Centres to the Malaysian Economy
flintglobalapac
 
OFFOFFBOX™ – A New Era for African Film | Startup Presentation
ambaicciwalkerbrian
 
Peak of Data & AI Encore - Real-Time Insights & Scalable Editing with ArcGIS
Safe Software
 
Trying to figure out MCP by actually building an app from scratch with open s...
Julien SIMON
 
AI and Robotics for Human Well-being.pptx
JAYMIN SUTHAR
 
Make GenAI investments go further with the Dell AI Factory
Principled Technologies
 
Responsible AI and AI Ethics - By Sylvester Ebhonu
Sylvester Ebhonu
 
Orbitly Pitch Deck|A Mission-Driven Platform for Side Project Collaboration (...
zz41354899
 
The-Ethical-Hackers-Imperative-Safeguarding-the-Digital-Frontier.pptx
sujalchauhan1305
 
GDG Cloud Munich - Intro - Luiz Carneiro - #BuildWithAI - July - Abdel.pdf
Luiz Carneiro
 
New ThousandEyes Product Innovations: Cisco Live June 2025
ThousandEyes
 
Presentation about Hardware and Software in Computer
snehamodhawadiya
 
NewMind AI Weekly Chronicles - July'25 - Week IV
NewMind AI
 
CIFDAQ's Market Wrap : Bears Back in Control?
CIFDAQ
 

Windows Phone 8 - 5 Application Lifecycle

  • 1. Oliver Scheer Senior Technical Evangelist Microsoft Deutschland http://the-oliver.com Application Lifecycle
  • 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
  • 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. 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) { }
  • 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. 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
  • 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. 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. 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
  • 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. 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
  • 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. 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. Demo 3: Dormant vs Tombstoned
  • 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. 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. 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. 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. Demo 4: Using State Dictionaries
  • 25. Running Under Lock Screen on Windows Phone
  • 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. 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. 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. 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. 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
  • 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
  • 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. 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. Standard App Relaunch Behavior ActiveDormant
  • 37. ‘True’ Background Location Tracking Behavior ActiveDormant Location Tracking
  • 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. 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. 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. 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. 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. 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. 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.