Windows Phone 8 Fundamental

48
Windows Phone 8 App Development 7 th April, 2013 Nguyen Pham [email protected] http://phamnguyen.info

Transcript of Windows Phone 8 Fundamental

Page 1: Windows Phone 8 Fundamental

Windows Phone 8

App Development

7th April, 2013

Nguyen Pham

[email protected]

http://phamnguyen.info

Page 2: Windows Phone 8 Fundamental

Windows Phone 8 Fundamentals

24/07/2013Microsoft confidential2

Windows Phone 8Features of the platform

• Lifecycle

• Data

• Background

• App2app

Page 3: Windows Phone 8 Fundamental

Application

Lifecycle

7th April, 2013

Page 4: Windows Phone 8 Fundamental

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

Page 5: Windows Phone 8 Fundamental

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

Page 6: Windows Phone 8 Fundamental

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";

Page 7: Windows Phone 8 Fundamental

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 tombstonedthis.State["incompleteEntry"] = this.logTextBox.Text;

}}

Page 8: Windows Phone 8 Fundamental

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 dataif (this.State.ContainsKey("incompleteEntry")){

this.logTextBox.Text = (string)this.State["incompleteEntry"];}

}

Page 9: Windows Phone 8 Fundamental

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();

}

Page 10: Windows Phone 8 Fundamental

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

Page 11: Windows Phone 8 Fundamental

Enabling FAR in Properties\WMAppManifest.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>

Page 12: Windows Phone 8 Fundamental

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 resumed24/07/201313

Page 13: Windows Phone 8 Fundamental

7th April, 2013

Files and Storage in

Windows Phone 8

Page 14: Windows Phone 8 Fundamental

File Type/ APIInstallation

FolderLocal Folder Example

Local Database data

contextappdata:/ 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 = awaitWindows.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

Page 15: Windows Phone 8 Fundamental

• 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

Page 16: Windows Phone 8 Fundamental

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

Page 17: Windows Phone 8 Fundamental

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();}

Page 18: Windows Phone 8 Fundamental

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;}

Page 19: Windows Phone 8 Fundamental

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

Page 20: Windows Phone 8 Fundamental

Saving Data – Using StorageFolder

private async void saveToLocalFolderAsync(string message){

// Get a reference to the Local FolderWindows.Storage.StorageFolder localFolder =

Windows.Storage.ApplicationData.Current.LocalFolder;

// Create the file in the local folder, or if it already exists, just open itWindows.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);}

}

Page 21: Windows Phone 8 Fundamental

Loading Data

private async string loadStringAsync(){string theData = string.Empty;

// Get a reference to the file in the Local FolderWindows.Storage.StorageFolder localFolder = Windows.Storage.ApplicationData.Current.LocalFolder;StorageFile storageFile = await localFolder.GetFileAsync(“Myfile.store"));

// Open it and read the contentsStream readStream = await storageFile.OpenStreamForReadAsync();using (StreamReader reader = new StreamReader(readStream)){theData = await reader.ReadToEndAsync();

}

return theData;}

Page 22: Windows Phone 8 Fundamental

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

Page 23: Windows Phone 8 Fundamental

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

Page 24: Windows Phone 8 Fundamental

• 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

Page 25: Windows Phone 8 Fundamental

7th April, 2013

Background

Agents

New updates

from

Background

Agent

Page 26: Windows Phone 8 Fundamental

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

Page 27: Windows Phone 8 Fundamental

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

Page 28: Windows Phone 8 Fundamental

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

Page 29: Windows Phone 8 Fundamental

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

Page 30: Windows Phone 8 Fundamental

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

Page 31: Windows Phone 8 Fundamental

Background Agent Functionality

Page 32: Windows Phone 8 Fundamental

• 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

Page 33: Windows Phone 8 Fundamental

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

Page 34: Windows Phone 8 Fundamental

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

Page 35: Windows Phone 8 Fundamental

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

Page 36: Windows Phone 8 Fundamental

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

Page 37: Windows Phone 8 Fundamental

7th April, 2013

App to App

Communication

This App This App

Page 38: Windows Phone 8 Fundamental

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

Page 39: Windows Phone 8 Fundamental

• 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

Page 40: Windows Phone 8 Fundamental

• 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

Page 41: Windows Phone 8 Fundamental

• 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

Page 42: Windows Phone 8 Fundamental

• 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

Page 43: Windows Phone 8 Fundamental

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

Page 44: Windows Phone 8 Fundamental

• 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);

}

Page 45: Windows Phone 8 Fundamental

• 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

Page 46: Windows Phone 8 Fundamental

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 AppsUse LaunchUriAsync to launch many of the built-in apps

24/07/2013Microsoft confidential52

Page 47: Windows Phone 8 Fundamental

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:reviewappLaunches 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=appLaunches the Store and searches for apps by keyword.

zune:search?publisher=[publisher name]Launches the Store and searches for items by publisher

name.

Page 48: Windows Phone 8 Fundamental

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.