The document discusses Windows Phone application icons, splash screens, and persisting application state when the application is tombstoned. It explains that when a user switches away from an application using the Start button, the application enters a tombstoned state and is given a chance to save its state before being deactivated from memory. Developers can add code to tombstone event methods like Application_Deactivated to save application data to isolated storage or memory when the application is tombstoned. This allows the application to restore its state when it is activated again by the user returning to it via the back button.
3. Topics The Windows Phone Start screen and Application List Icons in Sliverlight and XNA Customising Icons Splash Screens
4. 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
5. 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
6. 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
7. 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
8. The ApplicationIcon.png image The ApplicationIcon.png file holds the icon for the application in the Application List 8
9. The Background.png image The Background.png file holds the icon for the application in the Start Screen 9
10. 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
12. The Background.png image The Background.png file holds the Start screen image for an XNA game 12
13. 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
14. 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
15. 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
16. 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
17. 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
18. 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
20. 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
21. 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
22. 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
23. The Save button behaviour privatevoidsaveButton_Click(object sender, RoutedEventArgs e){saveText("jot.txt", jotTextBox.Text);} 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
24. The saveText method privatevoidsaveText(string filename, string text){using (IsolatedStorageFileisf =IsolatedStorageFile.GetUserStoreForApplication()) {using (IsolatedStorageFileStreamrawStream =isf.CreateFile(filename)) {StreamWriter writer = newStreamWriter(rawStream);writer.Write(text);writer.Close(); } }} The method can be used to save data in a file in isolated storage
25. Using IsolatedStorage privatevoidsaveText(string filename, string text){using (IsolatedStorageFileisf =IsolatedStorageFile.GetUserStoreForApplication()) {using (IsolatedStorageFileStreamrawStream =isf.CreateFile(filename)) {StreamWriter writer = newStreamWriter(rawStream);writer.Write(text);writer.Close(); } }} The method starts by getting a reference to the isolated storage for this application
26. Creating a file privatevoidsaveText(string filename, string text){using (IsolatedStorageFileisf =IsolatedStorageFile.GetUserStoreForApplication()) {using (IsolatedStorageFileStreamrawStream =isf.CreateFile(filename)) {StreamWriter writer = newStreamWriter(rawStream);writer.Write(text);writer.Close(); } }} This reference is then used to create a stream connected to the newly created file
27. Writing to the file privatevoidsaveText(string filename, string text){using (IsolatedStorageFileisf =IsolatedStorageFile.GetUserStoreForApplication()) {using (IsolatedStorageFileStreamrawStream =isf.CreateFile(filename)) {StreamWriter writer = newStreamWriter(rawStream);writer.Write(text);writer.Close(); } }} The method can now write data to the file and close it
28. The Load button behaviour privatevoidloadButton_Click(object sender, RoutedEventArgs e){string text;if ( loadText("jot.txt", out text ) ) {jotTextBox.Text = text; }else{jotTextBox.Text = "Type your jottings here...."; }} The load behaviour is more complex because a the file might not be available The load method displays a default message if loadText fails
29. Loading from Isolated storage try{using (IsolatedStorageFileStreamrawStream =isf.OpenFile(filename, System.IO.FileMode.Open)) {StreamReader reader = newStreamReader(rawStream); result = reader.ReadToEnd();reader.Close();}}catch {returnfalse;} This code reads a file from isolated storage It uses standard file input/output methods
30. 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
32. 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
33. 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
34. A Dictionary example classPerson{publicstring Name;publicstring Address;publicstring Phone;} 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
35. A Dictionary example Dictionary<string, Person> Personnel = newDictionary<string, Person>(); 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
36. Storing in the Dictionary Person p1 = newPerson { Name = "Rob", Address = "His House", Phone = "1234" };Personnel.Add(p1.Name, p1); 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
37. Reading from a Dictionary PersonfindPerson = Personnel["Rob"]; 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
38. Checking for Items if (Personnel.ContainsKey("Jim")){// If we get here the dictionary // contains Jim} 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
39. 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
40. 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
41. Saving using settings privatevoidsaveText(string filename, stringtext){IsolatedStorageSettingsisolatedStore =IsolatedStorageSettings.ApplicationSettings;isolatedStore.Remove(filename);isolatedStore.Add(filename, text);isolatedStore.Save();} This Save method stores a string of text with the supplied name
42. Getting the isolated store privatevoidsaveText(string filename, stringtext){IsolatedStorageSettingsisolatedStore =IsolatedStorageSettings.ApplicationSettings;isolatedStore.Remove(filename);isolatedStore.Add(filename, text);isolatedStore.Save();} This statement gets a reference to the settings object
43. Removing an old version privatevoidsaveText(string filename, stringtext){IsolatedStorageSettingsisolatedStore =IsolatedStorageSettings.ApplicationSettings;isolatedStore.Remove(filename);isolatedStore.Add(filename, text);isolatedStore.Save();} This removes an existing item with this name Removing does not fail if the item is not there
44. Saving the data privatevoidsaveText(string filename, stringtext){IsolatedStorageSettingsisolatedStore =IsolatedStorageSettings.ApplicationSettings;isolatedStore.Remove(filename);isolatedStore.Add(filename, text);isolatedStore.Save();} This adds the item and then saves the settings back to the isolated store
45. 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
46. 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
47. Loading from the setting storage privateboolloadText(string filename, outstring result) {IsolatedStorageSettingsisolatedStore = IsolatedStorageSettings.ApplicationSettings;result = "";try {result = (string)isolatedStore[filename];}catch {returnfalse;}returntrue;}
48. Managing the loading result = "";try {result = (string) isolatedStore[filename];}catch {returnfalse;} 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
49. 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
51. 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
53. Topics The Windows Phone process model Understanding “tombstoning” Tombstone events in applications Making use of tombstone events to manage application data storage and persistence
54. 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
55. 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
56. 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
57. 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
58. 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
59. 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
60. 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
61. 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
62. “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
63. 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
65. Saving on closing privatevoidApplication_Closing(object sender, ClosingEventArgse){MainPagejotPadPage = (MainPage)RootFrame.Content;jotPadPage.Save();} 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
66. MainPage Save method publicvoid Save(){saveText("jot.txt", jotTextBox.Text);} 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
67. 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
68. Saving on tombstoning privatevoidApplication_Deactivated(object sender, DeactivatedEventArgse){MainPagejotPadPage = (MainPage)RootFrame.Content;jotPadPage.SaveState();} The deactivated method looks very similar to the closing method It calls the SaveState method rather than the save method
69. Saving on tombstoning privatevoidApplication_Deactivated(object sender, DeactivatedEventArgse){MainPagejotPadPage = (MainPage)RootFrame.Content;jotPadPage.SaveState();} 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
70. The SaveStateText method privatevoidSaveStateText (string filename, string text){IDictionary<string, object> stateStore = PhoneApplicationService.Current.State;stateStore.Remove(filename);stateStore.Add(filename,text);} The PhoneApplicationService.Current.Stateobject works as a dictionary where a program can store state information It is in the Microsoft.Phone.Shell namespace
71. The loadStateText method privateboolloadStateText(string filename, outstring result) { IDictionary<string, object> stateStore = PhoneApplicationService.Current.State; result = ""; if (!stateStore.ContainsKey(filename)) returnfalse; result = (string)stateStore[filename]; returntrue; } The loadSaveState method fetches the value from the state storage
72. loadTextvsloadStateText 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
73. 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
74. 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
75. The Load method publicvoid 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...."; } }
76. Loading at program start privatevoidPhoneApplicationPage_Loaded(object sender, RoutedEventArgse) { Load(); } The program can call the Load method when the MainPageis loaded It can then copy all the data content into the user interface elements
77. 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
79. 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
81. 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
82. 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
83. 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
84. 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
85. 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
86. Launchers These are the Launchers available: PhoneCallTask EmailComposeTask SmsComposeTask SearchTask WebBrowserTask MediaPlayerLauncher MarketplaceDetailTask MarketplaceHubTask MarketplaceSearchTask 86
87. 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
88. The Mail button privatevoidmailButton_Click(object sender, RoutedEventArgse){sendMail("From JotPad", jotTextBox.Text);} 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
89. The Mail button privatevoidsendMail(string subject, string body){EmailComposeTask email = newEmailComposeTask();email.Body = body;email.Subject = subject;email.Show();} 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
90. The Tasks namespace usingMicrosoft.Phone.Tasks; 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
92. Choosers These are the Choosers available: CameraCaptureTask EmailAddressChooserTask PhoneNumberChooserTask PhotoChooserTask SaveEmailAddressTask SavePhoneNumberTask 92
93. 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
94. 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
95. Creating the PhotoChooserTask PhotoChooserTaskphotoChooser; publicMainPage() { InitializeComponent(); photoChooser = newPhotoChooserTask(); photoChooser.Completed+= newEventHandler<PhotoResult>(photoChooser_Completed); } The page constructor creates a PhotoChooserTask and binds a method to the Completed event
96. The Completed event handler voidphotoChooser_Completed(object sender, PhotoResult e) { if (e.TaskResult == TaskResult.OK) { selectedImage.Source = newBitmapImage(newUri(e.OriginalFileName)); } } The event handler for the completed event creates a new bitmap image from the filename in the result and displays this
97. The TaskResult field voidphotoChooser_Completed(object sender, PhotoResult e) { if (e.TaskResult == TaskResult.OK) { selectedImage.Source = newBitmapImage(newUri(e.OriginalFileName)); } } The TaskResult field in the result is set to TaskResult.OK if the user completed the choose action
98. The OriginalFileName field voidphotoChooser_Completed(object sender, PhotoResult e) { if (e.TaskResult == TaskResult.OK) { selectedImage.Source = newBitmapImage(newUri(e.OriginalFileName)); } } The result also contains the filename of the photo that was selected We can use this to create a URI to the image
99. Create a new image voidphotoChooser_Completed(object sender, PhotoResult e) { if (e.TaskResult == TaskResult.OK) { selectedImage.Source = newBitmapImage(newUri(e.OriginalFileName)); } } The program can create a new image from the URI and then set the source of the selected image to this
100. Load button event handler privatevoidloadButton_Click(object sender, RoutedEventArgse){photoChooser.Show();} When the Load button is pressed the event handler just calls the Show method on the chooser that was created in the form constructor
102. 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