Windows Phone Concepts

,Windows Phone Lifecycle

Windows Phone App Life Cycle, Own Work

Windows Phone Application Life Cycle

"Only one Windows Phone application is allowed to run in the foreground at a time."

  • The Application Life Cycle contains 3 states and 4 events which provides the illusion that multiple foreground applications are running at the same time. In actuality only one application can run in the foreground at a time. Other applications can be in a Dormant or Tombstoned state and can be Activated back to the running state by the user.

  • The 3 states in the application life cycle are:
    1. Running - the application is executing in the foreground. It has access to the computer resources and can be interacting with the user.
    2. Dormant - the application is still in memory, but is not executing. If the dormant app is Activated to run in the foreground again, the current app running in the foreground will then become dormant. Several apps can be in the Dormant state at the same time. Note: The dormant state did not existed in the versions before Windows Phone 7.5 (Mango).
    3. Tombstoned - is a dormant app that has been removed from memory. The application's state data has been saved to persistent storage so the Tombstoned app can be Activated to run in the foreground again. The Windows Phone operating system will move apps from the Dormant to the Tombstoned state when it needs more memory than is currently available. Up to five applications can be tombstoned at a time. After that limit, starting another application will cause the oldest tombstoned app to be terminated.
  • The 4 events in the application life cycle are:
    1. Launching - the only time a Launching event occurs is when an application is started from the Windows Phone Start screen.
    2. Closing - the only time the Closing event occurs is when an application terminates execution. It is recommended that Windows Phone applications do NOT have an Exit, or Close button to end the application. The desired way to end a WP application is to press the back button from the first page of the application.
    3. Deactivated- occurs when a user navigates away from the application by:
      • pressing the Start button.
      • accepting a phone call.
      • starting a Chooser task.
    4. Activated - occurs when a user revisits an app that is dormant or tombstoned. The property IsApplicationInstancePreserved inside the ActivatedEventArgs class is used inside the event to determine the state of the app which controls the appropriate logic for activating the app. TRUE means the application was dormant. FALSE means the application was tombstoned. The activation logic must complete in less than 10 seconds, else the app will terminate.
,Life Cycle Events and Methods

Page and Application States, Fair Use

Page and Application States

"Saved application state data makes it possible to resume running an application after it was made dormant or tombstoned."

  • A page state contains information about one particular page in the app. The information includes the data entered into the user controls. Saving the page state information allows the app to display previously entered user data when returning to a page. Page data is accessed:
    • through the State Dictionary provided by the PhoneApplicationPage.State property. The data must be serializable and should only be accessed in the methods:
      • OnNavigatedTo - retrieve the page state data during or after the method has been called.
      • OnNavigatedFrom - store the page state data during or before the method is called.
  • An application state contains information about the entire app. Saved application state data makes it possible to resume running an application after it was made dormant or tombstoned. Application state data is accessed:
    • through State Dictionary provided by the PhoneApplicationService.State property. The data must be serializable and should be accessed in:
      • Deactivated Event - store app state data to the property.
      • Activated Event - retrieve app state data from the property.
  • State data can also be stored using the applicationsettings property
    of the isolatedstoragesettings class (stores key-value pairs). However it is considerably slower that using the temporary storage provided by State Dictionaries. Microsoft recommends only using isolated storage for the long-term storage of data.

Background Processing

"In general, Windows Phone prevents third-party applications from running in the background. However there are some features, called Background Agents, that allow certain actions to be performed in the background."

Background Agents
  • Background Agents allow applications to execute code in the background, to do work for the initiating foreground application.
    • The code for background agents is derived from the BackgroundAgent class.
    • The background agent project is in the same solution as the foreground project. The same isolated storage area is shared by both the foreground and the background app.
    • The background and foreground apps could potentially run at the same time, so there may be a problem with concurrent data access. So you need to protect access to the files in isolated storage by using a named mutex.
    • You must explicitly reference the background task in the foreground task. (Note: No compiler error occurs if background task is not referenced. If background task is not working, check to make sure it has been referenced in the foreground project).
    • The background agent can run even when the main application is not in the foreground.
    • An application may have only one background agent. Further, only one instance of an agent can run at a time. However, the agent can be registered as a PeriodicTask(25 second mode), a ResourceIntensiveTask (10 minute mode) , or both. A parameter is passed into the agent app indicating where it is being called as periodic or resource-intensive. The code can look at this parameter value and branch to the appropriate code.
    • The number of agents allowed to be active at one time is restricted by the Windows Phone operating system.
    • If the right conditions do not arise, the agent will not be started. Background agents only run in situations where the operating system feels able to give them access to the processor.
    • If the phone goes into "Power Saver" mode, it may stop running background agents.
    • Users also have the option to disable the background agents running on their phone (They can be individually switched in the Settings menu).
    • You must not put any critical logic into background agents - because the background agent may never run.
    • A background agent is not equivalent to a foreground app running in the background. It is limited in what it can do and the access it has to the processor and other phone facilities. Only certain actions are allowed to be performed by a background agent:
      1. Allowed
        • Tiles
        • Toast
        • Location
        • Network
        • R/W Isolated Storage
        • Sockets
      2. Restricted
        • Display UI
        • XNA Libraries
        • Microphone and Camera
        • Sensors
        • Play audio (must only use background audio APIs
    • A task is the type of scheduling you request for a background agent. The task is managed by the operating system which runs the agent at the scheduled time. There are two types of tasks a background agent can perform:
      1. Periodic
        • Periodic agents typically run every 30 minutes. To optimize battery life, periodic agents may be run in alignment with other background processes and therefore the execution time may drift by up to 10 minutes. Periodic tasks are good for location tracking, polling background services, tile updates, etc.
        • Periodic agents typically run for 25 seconds. They can use no more than 6 MB of memory (Limit raised to 11 MB in WP 8.0).There are other constraints that may cause an agent to be terminated early. An agent will automatically become unscheduled after two consecutive crashes.
        • Battery Saver mode is an option that the user can enable on the device to indicate that battery life should be prioritized. If this mode is enabled, periodic agents may not run, even if the time interval has elapsed.
        • Periodic tasks are called from the foreground app, where you set an expiration time for the task (maximum time is 20 days). The foreground app will renew the schedule each time it is run. So if the foreground app has not been run with the expiration time, the corresponding background app will be unscheduled by the operating system.
        • To help maximize the battery life of the device, there is a hard limit on the number of periodic agents that can be scheduled on the phone. It varies per device configuration and can be as low as 6. There is another limit, which is lower than the hard limit, after which the user is warned that they have multiple background agents running and may, therefore, experience faster battery consumption.
      2. Resource Intensive
        • Resource-intensive agents typically run for 10 minutes. They can use no more than 6 MB of memory (Limit raised to 11 MB in WP 8.0). An agent will automatically become unscheduled after two consecutive crashes. Resource-intensive agents are good for synchronizing data with a server, preparing resources, compressing databases, etc.
        • Resource-intensive agents do not run unless the device is connected to an external power source.
        • Resource-intensive agents do not run unless the device has a network connection over Wi-Fi or through a connection to a PC.
        • Resource-intensive agents do not run unless the device screen is locked.
        • Resource-intensive agents do not run while a phone call is active
        • If a device reaches a state where all of the required conditions are met and a resource-intensive agent is launched, and then the device state changes so that any of the conditions are not met, the resource-intensive agent is terminated immediately.
.Streaming Audio

Computer Clip Art, Public Domain

Background Audio
  • The AudioPlayerAgent class is an implementation of a background agent specifically designed to play audio in the background. When an application registers an AudioPlayerAgent to run in the background, Windows Phone will be able to play audio when another application is in the foreground.

  • There are two types of background audio apps:
    1. Playing Media Files - creates a simple play list and passes a Uri containing the address of a media file to the Zune Media Queue to set the current track. The Uri can be local to the phone or a remote address. In either case, the audio needs to be of a type supported by Windows Phone for playback.

    2. Playing Streaming Media - uses the MediaStreamSource class to implement an audio stream to feed audio samples to the playback system.

Launchers and Choosers

"A major difference between launchers and choosers is that a chooser can return data back to the app, while a launcher can not."

  • The Launchers and Choosers APIs allow an application to access common operating system tasks such as taking a picture, retrieving contact information, or making a phone call.
    • The APIs start one of the built-in applications where the user can choose to complete or cancel the task. When the built-in application is closed, the calling application is usually reactivated.
    • Launchers and choosers help provide a consistent user experience in the Windows Phone platform.
    • Example of launchers and choosers are:
      • An example of a launcher would be using the EmailComposeTask object to send an email.
      • An example of a chooser would be using the PhotoChooserTask object to take a picture.

Google Map, Fair Use


"WP 7.x contained the GeoCoordinateWatcher class to determine geolocation. WP 8.0 introduced the Geolocator class that also determines geolocation ... and can additionally be run in the background."

  • All Windows Phone devices support geolocation.
    • Windows Phone devices contain GPS hardware to determine geographic location.
    • Windows Phone can also use Wi-Fi and cellular networks to determine geographic location.
    • The hardware GPS location is more accurate that the locations returned by the Wi-Fi and cellular networks.
    • However the hardware GPS consumes more battery power; only use hardware GPS when higher accuracy is required.
    • In WP 7.x the .NET location API (GeoCoordinateWatcher class can be used to determine the current geographical location expressed in longitude and latitude coordinates.
    • WP 8.0 introduced a new Geolocator class that also performs the location functions and, unlike GeoCoordinateWatcher class, can be run in the background.
,Touch Interface

Microsoft Surface, Fair Use

Touch Interface

Windows Phones are required to have at least a four-point multi-touch screen.

  • For simple touch gestures (tap, double-tap) the Touch Class provides an application-level service that processes multi-touch input from the operating system and raises the FrameReported event.

  • For complicated touch gestures that involve continuous motion (drag, flick, pinch), three primary manipulation events are:
    • ManipulationStarted - occurs when an input device begins a manipulation on the UIElement object.
    • ManipulationDelta - occurs when the input device changes position during a manipulation.
    • ManipulationCompleted - occurs when a manipulation and inertia on the UIElement object is complete.

    These events don’t report the activity of individual fingers. Instead, they consolidate the activity of multiple fingers into translation, scaling, and velocity information.

  • FrameReport Event for Simple Touch Gestures

    namespace PhoneApp3
        public partial class MainPage : PhoneApplicationPage
            // Constructor
            public MainPage()
                Touch.FrameReported += new TouchFrameEventHandler(OnFrameReported);         

            void OnFrameReported(object sender, TouchFrameEventArgs e)
                // TODO: Process the touch event


Reference Articles