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
24/07/2013
Not running
Running
LaunchingClosing
DeactivatingActivating
Dormant
5. 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
• When a new instance of an applicatPersistent 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
• ion 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
24/07/20135
6. 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";
7. 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;
}
}
8. 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"];
}
}
9. Manipulating the Back Stack
• This statement disables idle detection mode for your application
• It will now continue running under the lock screen
• An application can interrogate the back stack and also remove entries from it
• The method above would purge all the items in the stack
• A program can also enumerate the BackStack entries and find out where they point
• It is not possible to push entries onto the BackStack, nice though this would be
private void PurgeBackStackButton_Click(object sender, RoutedEventArgs e)
{
while (NavigationService.CanGoBack)
NavigationService.RemoveBackEntry();
}
10. 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 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
24/07/201311
11. 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>
12. 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 GPS 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
24/07/201313
14. File Type/ API
Installation
Folder
Local Folder Example
Local Database data
context
appdata:/ isostore:/
MyDataContext db = new MyDataContext
("isostore:/mydb.sdf")
Files access using
WP7.1 Isolated
Storage API
not supported
StorageFile and
StorageFolder
APIs
var isf =
IsolatedStorageFile.GetUserStoreForApplication()
File access using
Windows.Storage API
via URIs
ms-appx:///
ms-
appdata:///local/
var file = await
Windows.StorageFile.GetFileFromApplicationUriAsync(
new Uri("ms-appdata:///local/AppConfigSettings.xml"));
File access using
Windows.Storage API
via StorageFolder
references
Windows.
ApplicationModel.
Package.Current.
InstalledLocation
Windows.Storage.
ApplicationData.
Current.
LocalFolder
var localFolder =
Windows.Storage.ApplicationData.Current.LocalFolder;
Windows.Storage.StorageFile storageFile =
await localFolder.GetFileAsync("CaptainsLog.store");
24/07/2013Microsoft confidential18
Different Methods For Addressing Storage Locations
15. • Three ways of getting a reference to the same file:
// WP7.1 IsolatedStorage APIs
var isf = IsolatedStorageFile.GetUserStoreForApplication();
IsolatedStorageFileStream fs = new IsolatedStorageFileStream("CaptainsLog.store", FileMode.Open, isf));
...
// WP8 Storage APIs using URI
StorageFile storageFile = await Windows.Storage.StorageFile.GetFileFromApplicationUriAsync(
new Uri("ms-appdata:///local/CaptainsLog.store "));
...
// WP8 Storage APIs
Windows.Storage.StorageFolder localFolder = Windows.Storage.ApplicationData.Current.LocalFolder;
Windows.Storage.StorageFile storageFile = await localFolder.GetFileAsync("CaptainsLog.store");
...
WP8 File Access Alternatives
24/07/2013Microsoft confidential19
16. Application Settings
• If you just want to store setting information
• Username = “Fred”
• TextColor = “Green”
• ..you can use the ApplicationSettings object in Isolated Storage
• You use this as you would a dictionary
• You then write the object to persistent storage
17. Saving Data in Settings
• The storage works as a dictionary
• But you have to remember to call Save when you have finished adding keys
void saveString(string message, string name)
{
IsolatedStorageSettings.ApplicationSettings[name] =
message;
IsolatedStorageSettings.ApplicationSettings.Save();
}
18. Loading from Settings
• Test for the key before you try to find it or you will get an exception thrown
2
2
string loadString(string name)
{
if (IsolatedStorageSettings.ApplicationSettings.
Contains(name))
{
return (string)
IsolatedStorageSettings.ApplicationSettings[name];
}
else
return null;
}
19. Windows.Storage Classes
• Windows Phone Runtime storage classes are in the Windows.Storage
namespace
• StorageFolder
• Represents a storage area containing files and directories
• StorageFile
• Represents a file and provides methods for manipulating them
• Not supported on Windows Phone 8:
• ApplicationData.LocalSettings
• Use custom file or IsolatedStorageSettings
20. Saving Data – Using StorageFolder
private async void saveToLocalFolderAsync(string message)
{
// Get a reference to the Local Folder
Windows.Storage.StorageFolder localFolder =
Windows.Storage.ApplicationData.Current.LocalFolder;
// Create the file in the local folder, or if it already exists, just open it
Windows.Storage.StorageFile storageFile =
await localFolder.CreateFileAsync("Myfile.store",
CreationCollisionOption.OpenIfExists);
Stream writeStream = await storageFile.OpenStreamForWriteAsync();
using (StreamWriter writer = new StreamWriter(writeStream))
{
await writer.WriteAsync(logData);
}
}
21. Loading Data
private async string loadStringAsync()
{
string theData = string.Empty;
// Get a reference to the file in the Local Folder
Windows.Storage.StorageFolder localFolder = Windows.Storage.ApplicationData.Current.LocalFolder;
StorageFile storageFile = await localFolder.GetFileAsync(“Myfile.store"));
// Open it and read the contents
Stream readStream = await storageFile.OpenStreamForReadAsync();
using (StreamReader reader = new StreamReader(readStream))
{
theData = await reader.ReadToEndAsync();
}
return theData;
}
22. Local Folder
• All read-write I/O operations
restricted to local folder
• Create a files and folder structure
hierarchy
• Use Isolated Settings storage to
store application settings
23. Reserved Folders
• In addition to general data storage, the local folder
is used for the following special-use scenarios:
• Shared/Media - Apps can use this folder to
display album art in the Universal Volume Control
(UVC) while playing background audio
• Shared/ShellContent - Background images for
Tiles can be stored in isolated storage, but must
be located in this folder or a subfolder of it
• Shared/Transfers – Storage area used by the
Background File Transfer service
24/07/201329
24. • Windows Phone 8 devices support SD cards
• App can read files stored on a storage card
• Must declare the ID_CAP_REMOVABLE_STORAGE capability in the application
manifest file
• Cannot write files - Access is Read Only
• Can only access file types for which your app has registered a file association in
WMAppManifest.xml
External Storage (SD Card)
24/07/2013
26. Foreground Tasks
• Normally a Windows Phone application runs in the “foreground”
• Has access to screen and interacts directly with the user of the phone
• At any given time one application is running in the foreground
• Although others may be in the memory of the phone and can be selected
as required
• This is to ensure the best possible performance and battery life for the phone user
32
27. Background Agents
• A Windows Phone application can start a “background agent” to work for it
• It is a PeriodicTask, ResourceIntensiveTask or both at the same time
• There is only one agent allowed per application
• The agent can run when the main application is not in the foreground
• An agent is not equivalent to a foreground application running in the background
• It is limited in what it can do and the access it has to the processor
and other phone facilities
33
28. Agents and Tasks
• A Task is the scheduling type you request when you schedule a background agent to run
• It is managed by the operating system which runs the agent at the appointed time
• There are two kinds of Tasks
• Periodic tasks that are run every now and then
• Resource intensive tasks that run when the phone is in a position to let them
• The background Agent is the actual code functionality you write which runs in the
background and which does the work
• The agent code is implemented in a class that derives from BackgroundAgent
• The class is created as part of a Scheduled Task Agent Project
34
29. PeriodicTask Agents
• A PeriodicTask Agent runs every now and then
• Typically every 30 minutes or so, depending on loading on the phone
• It is intended to perform a task that should be performed regularly
and complete quickly
• The agent is allowed to run for 25 seconds or so
• Memory usage allowed<= 6 MB
• Unscheduled after two consecutive crashes
• The phone sets a limit on the maximum number of active agents at any time
• Good for location tracking, polling background services, tile updates
35
30. ResourceIntensive Agents
• Resource Intensive Agents run when the phone is in a position where it can usefully
perform some data processing:
• When the phone is powered by the mains
• When the battery is >90% charged
• When the phone is connected to WiFi
• When the phone is not being used (Lock screen displayed)
• A “resource intensive” agent can run for up to 10 minutes
• Memory usage allowed<= 6 MB
• Unscheduled after two consecutive crashes
• Good for synchronisation with a host service, unpacking/preparing resources, compressing
databases
36
32. • The code shown in this sample gets a new location whenever the Periodic agent runs
• Every 30 minutes or so
• Windows Phone 8 supports continuous background location tracking
• Suitable for Run Tracking apps and Turn-by-Turn navigation
• This is not covered here!
• See the Location and Maps module
Background Location Tracking
24/07/201338
33. Background Agent Tips
• Renew often
• You must reschedule agents from your foreground app at least every two weeks
• Do not implement critical functionality in a background agent
• User can disable them
• OS can suspend them in low battery situation
• If you need more reliable execution of code outside your application and need to update
Tiles or send Toast notifications, consider Push Notifications
34. 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 take place 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
40
35. 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
• Maximum number of Background Transfer Requests per app: 25
• Increased from 5 in Windows Phone OS 7.1
41
36. Audio Playback Agents
• 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
42
38. Agenda
24/07/2013Microsoft confidential44
File and Protocol
Associations
Launching Apps to Handle
Particular File Types
Launching one App from
Another
Auto-Launching with File and Protocol
Associations
Automatically launch your app when another app launches a
particular file type or protocol
File associations allow your app to launch to handle an email
attachment, a file opened in Internet Explorer or by another
app
39. • File associations allow your app to launch when the user wants to open a particular file
type, via:
• an email attachment
• a website via Internet Explorer
• a text message
• a Near Field Communications (NFC) tag
• another app from the Store
• Protocol association allows your app to automatically launch when another app launches a
special URI
• Protocol is the first part of a URI, e.g. myprotocol:/ShowProducts?CategoryID=aea6ae1f
• Your app launches another and passes it data in the remainder of the launch URI
Auto-launching with File and Protocol Associations
24/07/2013Microsoft confidential45
40. • Like Windows 8, Windows Phone 8 uses
LauncherLaunchFileAsync(IStorageFile) to launch a file and
LauncherLaunchUriAsync(Uri) to launch a URI
• However, the way Windows Phone XAML apps receive a file or
URI is different
• Windows 8 has a “default” Store app for a file type or URI, so that
will be launched
• In Windows Phone 8, if there are multiple Store apps installed that
can handle a particular file or protocol association, the user
chooses the receiving app from a menu
Comparison with Windows 8 User Experience
24/07/2013Microsoft confidential46
41. • To handle a particular file type, register for a file association in the app manifest file
• Optionally supply logos that Windows Phone OS will use when listing files
• Edit WMAppManifest.xml using the XML (Text) Editor
Registering for a File Association
24/07/2013Microsoft confidential47
Logo Size Use Dimensions
Small Email attachments 33x33 pixels
Medium Office hub list view 69x69 pixels
Large Browser download 176x176 pixels
42. • When your app is launched to handle a file, a deep link URI is sent to your app
/FileTypeAssociation?fileToken=89819279-4fe0-4531-9f57-d633f0949a19
• You need to implement a custom URI Mapper to parse the deep link URI and map to a
page in your app that will handle it
Listening for a file launch
24/07/2013Microsoft confidential48
FileTypeAssociation designates
that the source of the URI is a file type
association
The file token
43. Local Storage
SharedStorage
• Files passed to an app are stored by the OS
in a special folder called SharedStorage
• Receiving apps only have read access to
this folder
• Copy file to local storage to access it
Accessing the File
24/07/201349
44. • Your app can launch a file so another app can open it
Sending a File to Another App
24/07/201350
private async void LaunchFileButton_Click(object sender, RoutedEventArgs rea)
{
// Access local storage.
StorageFolder local = Windows.Storage.ApplicationData.Current.LocalFolder;
// Access the bug query file.
StorageFile bqfile = await local.GetFileAsync("file1.bqy");
// Launch the bug query file.
Windows.System.Launcher.LaunchFileAsync(bqfile);
}
45. • Many file extensions are reserved for the built-in apps
• .cer, .doc, .docx, .jpg, .mp3, .pptx … etc..
• Many more reserved by the OS
• .ade, .adp ….[ > 100 in total! ] … .xnk
• If you try to reserve a file association using one of the reserved types, the reservation
request will be ignored
• See the documentation for a full list of the reserved file types
Reserved File Associations
24/07/2013Microsoft confidential51
46. URI scheme Description
http:[URL]
Launches the web browser and navigates to the specified
URL.
mailto:[email address]
Launches the email app and creates a new message with the
specified email address on the To line.
Note that the email is not sent until the user taps send.
ms-settings-accounts: Launches the Account Settings app.
ms-settings-airplanemode: Launches the Airplane Mode Settings app.
ms-settings-bluetooth: Launches the Bluetooth Settings app.
ms-settings-cellular: Launches the Cellular Settings app.
ms-settings-emailandaccounts: Launches the email and accounts settings app.
ms-settings-location: Launches the Location Settings app.
ms-settings-lock: Launches the Lock Screen settings app.
ms-settings-wifi: Launches the Wi-Fi Settings app.
Launching Built-in Apps
Use LaunchUriAsync to launch many of the built-in apps
24/07/2013Microsoft confidential52
47. Launching Built-in Apps (cont)
24/07/2013Microsoft confidential53
URI scheme Description
zune:navigate?appid=[app ID]
Launches the Windows Phone Store and shows the details
page for the specified app.
zune:reviewapp
Launches the Store and shows the review page for the
calling app.
zune:reviewapp?appid=[app ID]
Launches the Store and shows the review page for the
specified app.
zune:search?[search parameter]=[value] Launches the Store and searches for the specified content.
zune:search?keyword=[search keyword]
&contenttype=app
Launches the Store and searches for apps by keyword.
zune:search?publisher=[publisher name]
Launches the Store and searches for items by publisher
name.