SlideShare una empresa de Scribd logo
1 de 48
Descargar para leer sin conexión
Windows Phone 8
App Development
7th April, 2013
Nguyen Pham
Pham.nguyen@Hotmail.com
http://phamnguyen.info
Windows Phone 8 Fundamentals
24/07/2013Microsoft confidential2
Windows Phone 8
Features of the platform
• Lifecycle
• Data
• Background
• App2app
Application
Lifecycle
7th April, 2013
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
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
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"];
}
}
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();
}
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
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 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
7th April, 2013
Files and Storage in
Windows Phone 8
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
• 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
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
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();
}
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;
}
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
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);
}
}
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;
}
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
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
• 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
7th April, 2013
Background
Agents
New updates
from
Background
Agent
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
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
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
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
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












Background Agent Functionality
• 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
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
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
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
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
7th April, 2013
App to App
Communication
This App   This App
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
• 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
• 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
• 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
• 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
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
• 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);
}
• 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
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
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.
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.

Más contenido relacionado

Similar a Windows Phone 8 Fundamental

Windows Phone 8 - 15 Location and Maps
Windows Phone 8 - 15 Location and MapsWindows Phone 8 - 15 Location and Maps
Windows Phone 8 - 15 Location and MapsOliver Scheer
 
Anatomy of android application
Anatomy of android applicationAnatomy of android application
Anatomy of android applicationNikunj Dhameliya
 
Android Activities.pdf
Android Activities.pdfAndroid Activities.pdf
Android Activities.pdfssusere71a07
 
Windows Phone 7: Navigating Between Pages
Windows Phone 7: Navigating Between PagesWindows Phone 7: Navigating Between Pages
Windows Phone 7: Navigating Between PagesJussi Pohjolainen
 
Windows phone 8 session 9
Windows phone 8 session 9Windows phone 8 session 9
Windows phone 8 session 9hitesh chothani
 
Html5 cache mechanism & local storage
Html5 cache mechanism & local storageHtml5 cache mechanism & local storage
Html5 cache mechanism & local storageSendhil Kumar Kannan
 
Architecting Single Activity Applications (With or Without Fragments)
Architecting Single Activity Applications (With or Without Fragments)Architecting Single Activity Applications (With or Without Fragments)
Architecting Single Activity Applications (With or Without Fragments)Gabor Varadi
 
App anatomy and life cycle
App anatomy and life cycleApp anatomy and life cycle
App anatomy and life cycleSV.CO
 
02 programmation mobile - android - (activity, view, fragment)
02 programmation mobile - android - (activity, view, fragment)02 programmation mobile - android - (activity, view, fragment)
02 programmation mobile - android - (activity, view, fragment)TECOS
 
HTML5 Local Storage
HTML5 Local StorageHTML5 Local Storage
HTML5 Local StorageLior Zamir
 
Mobile Devices
Mobile DevicesMobile Devices
Mobile DevicesYnon Perek
 
Presentation on Android application life cycle and saved instancestate
Presentation on Android application life cycle and saved instancestatePresentation on Android application life cycle and saved instancestate
Presentation on Android application life cycle and saved instancestateOsahon Gino Ediagbonya
 
Taking your “web” app to places you never expected - Ember Fest 2014
Taking your “web” app to places you never expected - Ember Fest 2014Taking your “web” app to places you never expected - Ember Fest 2014
Taking your “web” app to places you never expected - Ember Fest 2014williamsgarth
 
iOS Application Penetration Testing for Beginners
iOS Application Penetration Testing for BeginnersiOS Application Penetration Testing for Beginners
iOS Application Penetration Testing for BeginnersRyanISI
 
13.Windows Phone Store
13.Windows Phone Store13.Windows Phone Store
13.Windows Phone StoreNguyen Tuan
 
State Management in Mule applications | MuleSoft Mysore Meetup #42
State Management in Mule applications |  MuleSoft Mysore Meetup #42State Management in Mule applications |  MuleSoft Mysore Meetup #42
State Management in Mule applications | MuleSoft Mysore Meetup #42MysoreMuleSoftMeetup
 

Similar a Windows Phone 8 Fundamental (20)

Windows Phone 8 - 15 Location and Maps
Windows Phone 8 - 15 Location and MapsWindows Phone 8 - 15 Location and Maps
Windows Phone 8 - 15 Location and Maps
 
Anatomy of android application
Anatomy of android applicationAnatomy of android application
Anatomy of android application
 
Android Activities.pdf
Android Activities.pdfAndroid Activities.pdf
Android Activities.pdf
 
Windows Phone 7: Navigating Between Pages
Windows Phone 7: Navigating Between PagesWindows Phone 7: Navigating Between Pages
Windows Phone 7: Navigating Between Pages
 
Windows phone 8 session 9
Windows phone 8 session 9Windows phone 8 session 9
Windows phone 8 session 9
 
Html5 cache mechanism & local storage
Html5 cache mechanism & local storageHtml5 cache mechanism & local storage
Html5 cache mechanism & local storage
 
Architecting Single Activity Applications (With or Without Fragments)
Architecting Single Activity Applications (With or Without Fragments)Architecting Single Activity Applications (With or Without Fragments)
Architecting Single Activity Applications (With or Without Fragments)
 
App anatomy and life cycle
App anatomy and life cycleApp anatomy and life cycle
App anatomy and life cycle
 
02 programmation mobile - android - (activity, view, fragment)
02 programmation mobile - android - (activity, view, fragment)02 programmation mobile - android - (activity, view, fragment)
02 programmation mobile - android - (activity, view, fragment)
 
Session 1
Session 1Session 1
Session 1
 
HTML5 Local Storage
HTML5 Local StorageHTML5 Local Storage
HTML5 Local Storage
 
Mobile Devices
Mobile DevicesMobile Devices
Mobile Devices
 
Presentation on Android application life cycle and saved instancestate
Presentation on Android application life cycle and saved instancestatePresentation on Android application life cycle and saved instancestate
Presentation on Android application life cycle and saved instancestate
 
Taking your “web” app to places you never expected - Ember Fest 2014
Taking your “web” app to places you never expected - Ember Fest 2014Taking your “web” app to places you never expected - Ember Fest 2014
Taking your “web” app to places you never expected - Ember Fest 2014
 
iOS Application Penetration Testing for Beginners
iOS Application Penetration Testing for BeginnersiOS Application Penetration Testing for Beginners
iOS Application Penetration Testing for Beginners
 
13.Windows Phone Store
13.Windows Phone Store13.Windows Phone Store
13.Windows Phone Store
 
iOS Application Pentesting
iOS Application PentestingiOS Application Pentesting
iOS Application Pentesting
 
XPages Mobile, #dd13
XPages Mobile, #dd13XPages Mobile, #dd13
XPages Mobile, #dd13
 
Android Data Persistence
Android Data PersistenceAndroid Data Persistence
Android Data Persistence
 
State Management in Mule applications | MuleSoft Mysore Meetup #42
State Management in Mule applications |  MuleSoft Mysore Meetup #42State Management in Mule applications |  MuleSoft Mysore Meetup #42
State Management in Mule applications | MuleSoft Mysore Meetup #42
 

Más de Nguyên Phạm

What’s new in WinJS? Windows Phone 8.1 and the road ahead
What’s new in WinJS? Windows Phone 8.1 and the road aheadWhat’s new in WinJS? Windows Phone 8.1 and the road ahead
What’s new in WinJS? Windows Phone 8.1 and the road aheadNguyên Phạm
 
Building HTML and JavaScript Apps with KnockoutJS and MVVM
Building HTML and JavaScript Apps with KnockoutJS and MVVMBuilding HTML and JavaScript Apps with KnockoutJS and MVVM
Building HTML and JavaScript Apps with KnockoutJS and MVVMNguyên Phạm
 
7.imaging on windows phone
7.imaging on windows phone7.imaging on windows phone
7.imaging on windows phoneNguyên Phạm
 
Windows Phone 8 More Than An App
Windows Phone 8 More Than An AppWindows Phone 8 More Than An App
Windows Phone 8 More Than An AppNguyên Phạm
 
Windows Phone Development
Windows Phone DevelopmentWindows Phone Development
Windows Phone DevelopmentNguyên Phạm
 
Windows Phone 7 Platform Overview
Windows Phone 7 Platform OverviewWindows Phone 7 Platform Overview
Windows Phone 7 Platform OverviewNguyên Phạm
 
Windows Phone 7.5 Overview
Windows Phone 7.5 Overview Windows Phone 7.5 Overview
Windows Phone 7.5 Overview Nguyên Phạm
 
WP8 HTML5/IE10 for Developers
WP8 HTML5/IE10 for DevelopersWP8 HTML5/IE10 for Developers
WP8 HTML5/IE10 for DevelopersNguyên Phạm
 

Más de Nguyên Phạm (9)

What’s new in WinJS? Windows Phone 8.1 and the road ahead
What’s new in WinJS? Windows Phone 8.1 and the road aheadWhat’s new in WinJS? Windows Phone 8.1 and the road ahead
What’s new in WinJS? Windows Phone 8.1 and the road ahead
 
Building HTML and JavaScript Apps with KnockoutJS and MVVM
Building HTML and JavaScript Apps with KnockoutJS and MVVMBuilding HTML and JavaScript Apps with KnockoutJS and MVVM
Building HTML and JavaScript Apps with KnockoutJS and MVVM
 
7.imaging on windows phone
7.imaging on windows phone7.imaging on windows phone
7.imaging on windows phone
 
Windows Phone 8 More Than An App
Windows Phone 8 More Than An AppWindows Phone 8 More Than An App
Windows Phone 8 More Than An App
 
Expression Blend
Expression BlendExpression Blend
Expression Blend
 
Windows Phone Development
Windows Phone DevelopmentWindows Phone Development
Windows Phone Development
 
Windows Phone 7 Platform Overview
Windows Phone 7 Platform OverviewWindows Phone 7 Platform Overview
Windows Phone 7 Platform Overview
 
Windows Phone 7.5 Overview
Windows Phone 7.5 Overview Windows Phone 7.5 Overview
Windows Phone 7.5 Overview
 
WP8 HTML5/IE10 for Developers
WP8 HTML5/IE10 for DevelopersWP8 HTML5/IE10 for Developers
WP8 HTML5/IE10 for Developers
 

Último

"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr LapshynFwdays
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):comworks
 
Search Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfSearch Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfRankYa
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticscarlostorres15106
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationRidwan Fadjar
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfAddepto
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machinePadma Pradeep
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsRizwan Syed
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Scott Keck-Warren
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfAlex Barbosa Coqueiro
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsSergiu Bodiu
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Mattias Andersson
 
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostLeverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostZilliz
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationSafe Software
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubKalema Edgar
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
The Future of Software Development - Devin AI Innovative Approach.pdf
The Future of Software Development - Devin AI Innovative Approach.pdfThe Future of Software Development - Devin AI Innovative Approach.pdf
The Future of Software Development - Devin AI Innovative Approach.pdfSeasiaInfotech2
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyAlfredo García Lavilla
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek SchlawackFwdays
 

Último (20)

"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):
 
Search Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfSearch Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdf
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 Presentation
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdf
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machine
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL Certs
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdf
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platforms
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?
 
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostLeverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding Club
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
The Future of Software Development - Devin AI Innovative Approach.pdf
The Future of Software Development - Devin AI Innovative Approach.pdfThe Future of Software Development - Devin AI Innovative Approach.pdf
The Future of Software Development - Devin AI Innovative Approach.pdf
 
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptxE-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easy
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
 

Windows Phone 8 Fundamental

  • 1. Windows Phone 8 App Development 7th April, 2013 Nguyen Pham Pham.nguyen@Hotmail.com http://phamnguyen.info
  • 2. Windows Phone 8 Fundamentals 24/07/2013Microsoft confidential2 Windows Phone 8 Features of the platform • Lifecycle • Data • Background • App2app
  • 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
  • 13. 7th April, 2013 Files and Storage in Windows Phone 8
  • 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
  • 25. 7th April, 2013 Background Agents New updates from Background Agent
  • 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
  • 37. 7th April, 2013 App to App Communication This App   This App
  • 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.
  • 48. 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.