wp7 hub_creando aplicaciones de windows phone
DESCRIPTION
Fase 3.6TRANSCRIPT
Creating Windows Phone Applications
WINODWS PHONE ICONS AND SPLASH SCREENS
Topics The Windows Phone Start screen and Application
List Icons in Sliverlight and XNA Customising Icons Splash Screens
The Windows Phone UI The Windows Phone user interface is quite different
from any other Microsoft Windows interface Users can “pin” frequently used applications to the
Start screen A user can always navigate to the Start screen by
pressing the Start button on the phone From the Start screen a user can move to the
Application list
4
The Start Screen The default start screen contains
links to built in Windows Phone features
Users can add their favourite contacts, media and applications to the screen
Each application is represented by a tile
5
The Application List This is a list of all the
applications on the phone Each application is represented
by its icon and the title of the application
6
Icons in a Silverlight program When you create a
Silverlight application Visual Studio creates default versions of the icon files
We can edit the files to make custom items
7
The ApplicationIcon.png image
The ApplicationIcon.png file holds the icon for the application in the Application List
8
The Background.png image
The Background.png file holds the icon for the application in the Start Screen
9
Icons in an XNA program
The icons for an XNA program are different
The file names are different and there is also an icon for use if a game is deployed to an Xbox 360
10
The GameThumbnail.png image
The GameThumbnail.png file holds the application icon for an XNA game
11
The Background.png image
The Background.png file holds the Start screen image for an XNA game
12
Customising Icons It is important to create good looking icons for your
programs These icons will also be used to brand your program
in the Windows Phone Marketplace This is probably something worth employing an
artist for…
13
Splash Screens A splash screen is an image that is displayed as a
program starts running They are often used to brand an application and
give a user something to watch as a program loads itself into memory
14
Silverlight Splash Screens Silverlight applications are
provided with a default splash screen image which just shows a clock
You can replace this with a jpeg image of your own
The file is called SplashScreenImage.jpg
15
Splash screens in XNA XNA projects do not have a splash screen by default An XNA game is expected to load its content and
then start drawing the screen The Windows Phone operating system expects an
application to start drawing on the screen within 5 seconds of starting running
It is quite possible that large amounts of content will take longer than this to load
16
XNA Loading Strategies If you make a game with a large amount of content
you should not load it all in the LoadContent method for the game
Instead the game should load a splash screen and display that while a background thread loads the content into memory
It is important to manage the content loading process in an XNA game and only load what you need at any point in the game
17
Summary Applications and games on Windows Phone are
given icons to identify them There are images for the application on the Start
screen and also in the Application list Silverlight applications also have a splash screen
image which is displayed when they start running XNA developers do not have a splash screen
provided but games with lots of content may need to display one
PERSISTING DATA IN ISOLATED STORAGE
Topics Windows Phone applications and isolated storage Using isolated storage to store files Storing name/value pairs
An introduction to the Dictionary collection class Storing settings information in Isolated Storage
Isolated Storage This storage is called isolated because each
application on the phone has its own area One application cannot access the storage of
another The data is stored in the mass storage of the phone
A program can store very large amounts of data in isolated storage
21
Jotpad program This is the first version of the
jotpad program It displays a textbox for the
user to enter text It also has Load and Save
buttons that can be used to load and save the jotted text to isolated storage
22
The Save button behaviour
When the user presses the Save button the event hander calls a method to save the text from the TextBox into a file
The saveText method is also given the name of the file to save the text in
private void saveButton_Click(object sender, RoutedEventArgs e)
{
saveText("jot.txt", jotTextBox.Text);
}
The saveText method
The method can be used to save data in a file in isolated storage
private void saveText(string filename, string text)
{
using (IsolatedStorageFile isf =
IsolatedStorageFile.GetUserStoreForApplication())
{
using (IsolatedStorageFileStream rawStream =
isf.CreateFile(filename)) {
StreamWriter writer = new StreamWriter(rawStream);
writer.Write(text);
writer.Close();
}
}
}
Using IsolatedStorage
The method starts by getting a reference to the isolated storage for this application
private void saveText(string filename, string text)
{
using (IsolatedStorageFile isf =
IsolatedStorageFile.GetUserStoreForApplication())
{
using (IsolatedStorageFileStream rawStream =
isf.CreateFile(filename)) {
StreamWriter writer = new StreamWriter(rawStream);
writer.Write(text);
writer.Close();
}
}
}
Creating a file
This reference is then used to create a stream connected to the newly created file
private void saveText(string filename, string text)
{
using (IsolatedStorageFile isf =
IsolatedStorageFile.GetUserStoreForApplication())
{
using (IsolatedStorageFileStream rawStream =
isf.CreateFile(filename)) {
StreamWriter writer = new StreamWriter(rawStream);
writer.Write(text);
writer.Close();
}
}
}
Writing to the file
The method can now write data to the file and close it
private void saveText(string filename, string text)
{
using (IsolatedStorageFile isf =
IsolatedStorageFile.GetUserStoreForApplication())
{
using (IsolatedStorageFileStream rawStream =
isf.CreateFile(filename)) {
StreamWriter writer = new StreamWriter(rawStream);
writer.Write(text);
writer.Close();
}
}
}
The Load button behaviour
The load behaviour is more complex because a the file might not be available
The load method displays a default message if loadText fails
private void loadButton_Click(object sender, RoutedEventArgs e)
{
string text;
if ( loadText("jot.txt", out text ) ) {
jotTextBox.Text = text;
}
else {
jotTextBox.Text = "Type your jottings here....";
}
}
Loading from Isolated storage
This code reads a file from isolated storage It uses standard file input/output methods
try
{
using (IsolatedStorageFileStream rawStream =
isf.OpenFile(filename, System.IO.FileMode.Open))
{
StreamReader reader = new StreamReader(rawStream);
result = reader.ReadToEnd();
reader.Close();
}
}
catch
{
return false;
}
The Isolated Storage File Store
Your applications can create many files in isolated storage
They can also build up a directory hierarchy within the storage
You can perform stream based input/output with files in the isolated storage
30
31
Demo 1: Jotpad Demo
Demo
Using Settings Isolated storage Creating files in isolated storage is useful, but often
a program only wants to store name/value pairs Examples of this:
Username Home directory Colour and display preferences
The Isolated storage in Windows Phone also provides setting storage
32
Settings and Dictionaries The settings storage works like a Dictionary
collection A Dictionary holds a collection of a particular type
which is indexed by key values of another type Programs can look up items based on the value of
the key
33
A Dictionary example
The Person class holds information about a given person in our system
The Person class could contain many more data properties than the ones above
We need to store and find Person items
class Person
{
public string Name;
public string Address;
public string Phone;
}
A Dictionary example
This creates a Dictionary called Personnel This holds a collection of Person records that are
indexed on a string Generics are used to give the types of the index
item and the data stored We could use the name of the person as the index
item
Dictionary<string, Person> Personnel =
new Dictionary<string, Person>();
Storing in the Dictionary
This creates a Person value and adds it to the dictionary
The name value is used as the key The dictionary will not allow duplicate keys
Person p1 = new Person { Name = "Rob",
Address = "His House",
Phone = "1234"
};
Personnel.Add(p1.Name, p1);
Reading from a Dictionary
We can use a string indexer to locate items in the dictionary
The Personnel dictionary will return Person values If the item cannot be found this statement will throw
an exception
Person findPerson = Personnel["Rob"];
Checking for Items
A Dictionary also provides a method that can be used to test for the existence of particular keys
Your code should do this rather than throw exceptions
if (Personnel.ContainsKey("Jim"))
{
// If we get here the dictionary
// contains Jim
}
Dictionaries in action Dictionaries are very useful for storing collections
that you want to index on a particular key value The storing and searching is managed very
efficiently A system can contain multiple dictionaries to index
on different key items A program can also iterate through the dictionary
contents
39
Dictionaries and Isolated Storage The IsolatedStorageSettings class provides a
Dictionary based model for storing and retrieving setting information
It stores any object indexed on a string key This makes it very easy to store settings objects Your application must call the “Save” method on
the settings object to complete a save
40
Saving using settings
This Save method stores a string of text with the supplied name
private void saveText(string filename,
string text)
{
IsolatedStorageSettings isolatedStore =
IsolatedStorageSettings.ApplicationSettings;
isolatedStore.Remove(filename);
isolatedStore.Add(filename, text);
isolatedStore.Save();
}
Getting the isolated store
This statement gets a reference to the settings object
private void saveText(string filename,
string text)
{
IsolatedStorageSettings isolatedStore =
IsolatedStorageSettings.ApplicationSettings;
isolatedStore.Remove(filename);
isolatedStore.Add(filename, text);
isolatedStore.Save();
}
Removing an old version
This removes an existing item with this name Removing does not fail if the item is not there
private void saveText(string filename,
string text)
{
IsolatedStorageSettings isolatedStore =
IsolatedStorageSettings.ApplicationSettings;
isolatedStore.Remove(filename);
isolatedStore.Add(filename, text);
isolatedStore.Save();
}
Saving the data
This adds the item and then saves the settings back to the isolated store
private void saveText(string filename,
string text)
{
IsolatedStorageSettings isolatedStore =
IsolatedStorageSettings.ApplicationSettings;
isolatedStore.Remove(filename);
isolatedStore.Add(filename, text);
isolatedStore.Save();
}
Saving items You can save objects other than strings Each object must have a unique name Your program must call the Save method to persist
the settings information when it has been added to the settings object
45
Reading from settings storage Reading is the reverse of writing Your program must provide the key of the item it
wants to load Note that the saved item will be returned in the
form of an object reference which your program must cast to the required type
The settings storage does not provide a ContainsKey method
46
Loading from the setting storage
private bool loadText(string filename,
out string result) {
IsolatedStorageSettings isolatedStore =
IsolatedStorageSettings.ApplicationSettings;
result = "";
try {
result = (string)isolatedStore[filename];
}
catch {
return false;
}
return true;
}
Managing the loading
Because it is not possible to check if a setting exists the load method must instead catch the exception that is thrown if a key is not found
The loatText method returns false to indicate that the load failed
48
result = "";
try {
result = (string) isolatedStore[filename];
}
catch {
return false;
}
Isolated Storage A program can create and use as many files as the
application requires It is also possible to create folders within isolated
storage so an application can organise data as required
The data will be persisted when the application is not running
If the application is removed from the phone all its isolated storage is deleted
49
50
Demo 2: Settings Jotpad
Demo
Summary Windows Phone provides “local” storage for
applications Data stored is local to an application and not shared
with or visible to others There is a local filesystem and a dictionary based
setting store which can be used for name/value pairs
PERSISTING APPLICATION STATE
Topics The Windows Phone process model Understanding “tombstoning” Tombstone events in applications Making use of tombstone events to manage
application data storage and persistence
Windows Phone Task Management
The Windows Phone platform uses a multi-tasking operating system
This allows phone functions to operate simultaneously You can listen to music and read your email
However, this multi-tasking ability is not extended to applications that we write
54
Single Tasking Applications In the present version of Windows Phone it is not
possible to run more than one application at the same time
Applications are started and stopped in sequence If the user decides to do something different the
currently running application will be stopped
55
Why Single Task? Removing multi-tasking stops one application from
being affected by another as it runs Background tasks can impact on performance
and battery life The limited screen space available to an application
makes it hard to manage multiple programs at the same time
The Windows Phone design does provide for fast task switching by the user
56
The Back and Start buttons
The Back button can be used to exit from one program and return to one being used earlier
The system maintains a stack of applications to allow navigation in and out of tasks
Pressing Start opens up the Start menu so that a new application can be selected
It is easy to return to a feature you left by pressing the Start button
57
Application Switching This means that an application must be adept at
stopping and starting The aim is to present the appearance that the
application was never stopped at all When a user returns to an application they were
using it should be exactly how they left it The application must store and retrieve its state to
achieve this
58
Tombstoning Tombstoning is the name given to the act of
stopping an application so that a user can start another
If the user presses the Start button when an application is running that application will be “tombstoned”
It is sent an event to signal that it is about to be removed from memory and has a few seconds to save its state and tidy up
59
Tombstones and code design The way that a program responds to tombstone
events has an impact on the user experience If a user “abandons” an application by pressing
Start they might not expect it to retain data they have entered Start might be used as a quick way of cancelling
an activity You need think about this at design time
60
Jotpad and tombstones We are going to make the Jotpad program
“tombstone friendly” The program will automatically persist data when
the user exits and load on entry It will also store data when it is tombstoned Initially we will use the isolated storage To do this we need to add code to the tombstone
event methods
61
“Tombstone” events There are four “tombstone” events
Launching – a new copy of the program has been started by the user
Closing - the program is ending normally Deactivated – the user has pressed Start to run
another program (tombstone in progress) Activated – the program is being started as a
result of the Back button being used
62
Tombstone event methods Each of the events is mapped onto a method in the
App.xaml.cs file By adding code into these methods an application
can get control when the event occurs The code in the method can load or save program
status as appropriate
63
Tombstone event methodsprivate void Application_Launching(object sender,
LaunchingEventArgs e)
{
}
private void Application_Activated(object sender,
ActivatedEventArgs e)
{
}
private void Application_Deactivated(object sender,
DeactivatedEventArgs e)
{
}
private void Application_Closing(object sender,
ClosingEventArgs e)
{
}
Saving on closing
The closing method gets a reference to the mainPage of the application and calls the Save behaviour on that page
This removes the need for a Save button Jotpad now saves the text automatically
private void Application_Closing(object sender,
ClosingEventArgs e)
{
MainPage jotPadPage = (MainPage)RootFrame.Content;
jotPadPage.Save();
}
MainPage Save method
This is the Save method in the MainPage for the JotPad application
It calls the saveText method to save the text from the textbox
It is now public so it can be used from outside the MainPage class
public void Save()
{
saveText("jot.txt", jotTextBox.Text);
}
Saving to memory The save methods that we have seen up to now use
persistent storage to hold status This can be slow and hard to use if you just want to
store the current status of the user interface Windows Phone provides a way that an application
can store status information in memory when it is tombstoned
67
Saving on tombstoning
The deactivated method looks very similar to the closing method
It calls the SaveState method rather than the save method
private void Application_Deactivated(object sender,
DeactivatedEventArgs e)
{
MainPage jotPadPage = (MainPage)RootFrame.Content;
jotPadPage.SaveState();
}
Saving on tombstoning
The deactivated method looks very similar to the closing method which runs when the application closes
It calls the SaveState method rather than the Save method
private void Application_Deactivated(object sender,
DeactivatedEventArgs e)
{
MainPage jotPadPage = (MainPage)RootFrame.Content;
jotPadPage.SaveState();
}
The SaveStateText method
The PhoneApplicationService.Current.State object works as a dictionary where a program can store state information
It is in the Microsoft.Phone.Shell namespace
private void SaveStateText (string filename, string text)
{
IDictionary<string, object> stateStore =
PhoneApplicationService.Current.State;
stateStore.Remove(filename);
stateStore.Add(filename,text);
}
The loadStateText methodprivate bool loadStateText(string filename,
out string result)
{
IDictionary<string, object> stateStore =
PhoneApplicationService.Current.State;
result = "";
if (!stateStore.ContainsKey(filename)) return false;
result = (string)stateStore[filename];
return true;
}
The loadSaveState method fetches the value from the state storage
loadText vs loadStateText The loadStateText method is very similar to the loadState method
They are both used in exactly the same way One saves to isolated storage One saves to the state object
They both have exactly the same signature and can be used interchangeably
This reflects good design
72
Reloading data when restarted A program can get Launching or Activated
messages when it restarts Launching means a new copy is starting Activated means that it is restarted after being
tombstoned Unfortunately these events occur before any of the
Silverlight user interface components have been created
They can’t be used to actually load data
73
Loading data on restart The JotPad program tries to load from the state
memory first and then loads from isolated storage if this fails
This is appropriate behaviour for this application It might not be appropriate for all programs
however For some applications the user might want to
press Start to abandon their input
74
The Load methodpublic void Load()
{
string text;
if (loadStateText("jot.txt", out text)) {
jotTextBox.Text = text;
return;
}
if (loadText("jot.txt", out text)) {
jotTextBox.Text = text;
}
else
{
jotTextBox.Text = "Type your jottings here....";
}
}
Loading at program start
The program can call the Load method when the MainPage is loaded
It can then copy all the data content into the user interface elements
private void PhoneApplicationPage_Loaded(object sender,
RoutedEventArgs e)
{
Load();
}
Using Visual Studio Visual Studio retains contact with an application
when it is tombstoned If you press the Start button on device or
Emulator while debugging a program If the application is reactivated Visual Studio will
continue debugging This makes it easy to debug the code that manages
tombstoning in your applications
77
78
Demo 1: Jotpad Demo
Demo
Summary The Windows Phone operating system uses a single
tasking model for applications Start and Back buttons are used by the user to
quickly switch between applications Applications can bind to “tombstone” events so that
they can save and load their state Windows Phone provides state memory that an
application can use to retain data if it is stopped
LAUNCHERS AND CHOOSERS
Topics Launchers and choosers in context Tombstoning and Launchers and Choosers Using a Launcher
Starting an application and returning from it Using a Chooser
Starting an application and using the result that is returned
Launchers and Choosers Windows Phone provides a way for programs to
interact with the phone itself: Take photographs Place phone calls Interact with the address book Select media
Now we are going to find out how to do this
82
User Involvement Note that in all the applications the user is directly
involved and has the final say on the action A program cannot just take a photograph, place a
call or send and SMS The user must confirm these operations before they
complete An application can only initiate the action
83
Launchers vs Choosers Applications call a Launcher makes use of a phone
feature Place a phone call, send an email or SMS
A Chooser is used to select something Take a picture and return it Select an email address
Both are used in the same way, but a Chooser will generate an event that delivers the result
84
Calling a Launcher or Chooser When an application calls a Launcher or Chooser
the new task gets control When the task is complete the application regains
control If the user never returns from the Launcher/Chooser
the application never gets control back This when the new task gets control an application
may get tombstoned
85
Launchers These are the Launchers available:
PhoneCallTask EmailComposeTask SmsComposeTask SearchTask WebBrowserTask MediaPlayerLauncher MarketplaceDetailTask MarketplaceHubTask MarketplaceSearchTask
86
Using a Launcher As an example, we could add an
email feature to the JotPad application
This would allow the user to send a jotting as an email
When the Mail button is pressed the EmailComposeTask is started
87
The Mail button
When the user clicks the mail button the event handler calls the sendMail method
This is given the title and text of the email that is to be sent
private void mailButton_Click(object sender,
RoutedEventArgs e)
{
sendMail("From JotPad", jotTextBox.Text);
}
The Mail button
The sendMail method creates an EmailComposeTask instance and then calls Show on that instance
When the email has been sent the jotPad program will resume
private void sendMail(string subject, string body)
{
EmailComposeTask email = new EmailComposeTask();
email.Body = body;
email.Subject = subject;
email.Show();
}
The Tasks namespace
In order to use the Launcher and Chooser classes by name an application should add the above namespace
Otherwise you will have to use the fully formed version of the class names
using Microsoft.Phone.Tasks;
91
Demo 1: Email Jotpad
Demo
Choosers These are the Choosers available:
CameraCaptureTask EmailAddressChooserTask PhoneNumberChooserTask PhotoChooserTask SaveEmailAddressTask SavePhoneNumberTask
92
Choosers Before an application calls a chooser it can bind to
an event that the chooser task generates This is used to deliver a result object to the
application when it regains control Choosers must be created in the constructor for a
page and declared as members of the page class
93
Picture display application The picture display application
uses the PhotoChooserTask to allow the user to select a picture for display
It then displays this on the phone screen
94
Creating the PhotoChooserTask
The page constructor creates a PhotoChooserTask and binds a method to the Completed event
PhotoChooserTask photoChooser;
public MainPage()
{
InitializeComponent();
photoChooser = new PhotoChooserTask();
photoChooser.Completed +=
new EventHandler<PhotoResult>(photoChooser_Completed);
}
The Completed event handler
The event handler for the completed event creates a new bitmap image from the filename in the result and displays this
void photoChooser_Completed(object sender, PhotoResult e)
{
if (e.TaskResult == TaskResult.OK)
{
selectedImage.Source =
new BitmapImage(new Uri(e.OriginalFileName));
}
}
The TaskResult field
The TaskResult field in the result is set to TaskResult.OK if the user completed the choose action
void photoChooser_Completed(object sender, PhotoResult e)
{
if (e.TaskResult == TaskResult.OK)
{
selectedImage.Source =
new BitmapImage(new Uri(e.OriginalFileName));
}
}
The OriginalFileName field
The result also contains the filename of the photo that was selected
We can use this to create a URI to the image
void photoChooser_Completed(object sender, PhotoResult e)
{
if (e.TaskResult == TaskResult.OK)
{
selectedImage.Source =
new BitmapImage(new Uri(e.OriginalFileName));
}
}
Create a new image
The program can create a new image from the URI and then set the source of the selected image to this
void photoChooser_Completed(object sender, PhotoResult e)
{
if (e.TaskResult == TaskResult.OK)
{
selectedImage.Source =
new BitmapImage(new Uri(e.OriginalFileName));
}
}
Load button event handler
When the Load button is pressed the event handler just calls the Show method on the chooser that was created in the form constructor
private void loadButton_Click(object sender,
RoutedEventArgs e)
{
photoChooser.Show();
}
101
Demo 2: Picture display
Demo
Summary Launchers and Choosers provide a way that
applications can use phone features Launchers just start a phone feature running
whereas a Chooser can return a result When a Launcher or Chooser is invoked the running
application is tombstoned A Chooser will fire an event method in the
application when/if it returns