July 2013

Volume 28 Number 7

Windows 8 - Building Apps for Windows 8 and Windows Phone 8

By Joel Reyes | July 2013

Windows 8 and Windows Phone 8 are on a path toward convergence. In the meantime, developers interested in building for both platforms must understand the major similarities and differences between the two. Learning where the Windows 8 and Windows Phone Runtime APIs currently intersect gives you the best opportunity to deliver applications for both, leveraging much of the same knowledge, tools, code and assets. In this article I’ll explore these differences and commonalties to help you understand what is and is not possible before you start building a solution that targets both platforms.

The consistency in the UX—the use of tiles, the rich touch interface, the app bar and navigation—simplifies application design and implementation for both platforms. And the adoption of a common API surface area facilitates code sharing for a lot of scenarios. You can choose the right technologies for your apps: C#, Visual Basic or C++, or a hybrid for both platforms. The resources found at aka.ms/sharecode contain great info about creating applications that run on Windows Phone 8 and Windows 8, and present code-sharing techniques to maximize code reuse when building for both.

Specific Areas of Comparison

In order to effectively write for both platforms, you need to understand the major feature differences, as well as the features that at a high level appear similar, but have different APIs and implementations. For those features, code reuse should not be attempted. I’ll examine three key areas of concern:

  • UX
  • Data model and supporting code
  • Platform-specific features

UX

Form factors are a major consideration when designing the UI for a cross-platform app. You need to consider attributes such as screen resolutions, screen sizes and default device orientation. Careful UI decisions must be made to ensure that the experience is optimized for the user given the constraints of the particular device.

You’ll quickly realize that it doesn’t make sense to include all features of a Windows Store app in a Windows Phone 8 app and that you must design a native UX for each platform. Figure 1 shows examples of the kind of UX differences you’ll have to consider to build the best experience possible.

Figure 1 A Comparison of Windows Phone 8 and Windows 8 UX Features

Windows Phone 8 Windows 8
One-handed touch most common One or two-handed touch, mouse
Guaranteed hardware, such as camera and accelerometer No guarantee of any specific hardware, must check at run time
Avoid multiple columns of content Rows and columns of content can work well
Scroll vertically for more content; limited room on the app bar Scroll horizontally for more content; significant room on the app bar
Hardware back button On-screen back button
No semantic zoom Semantic zoom

XAML Namespaces Even though both Windows 8 and Windows Phone 8 use XAML for UI design, don’t expect to reuse XAML across your apps. There are major differences in the platforms—page layout and orientation, XAML namespaces and XAML controls—that make this challenging. 

Although many controls exist for both platforms, they reside in different namespaces. For instance, Windows 8 controls equivalents for Windows Phone can be found in Windows.UIXaml.Controls, as well as in the Microsoft.Phone.Controls and Microsoft.Phone.Shell, while System.Windows.Controls contains Windows 8 controls and some shared controls. Luckily, the XAML editor will alert you when you attempt to add an unsupported control. However, XAML doesn’t support conditional compilation, so there’s no easy way to include namespaces for one platform or the other at run time.

XAML Controls Each library of controls is optimized for its corresponding platform. Consequently, it’s highly recommended that you design your own user controls separately for each platform. This will help maintain a consistent UX on each platform while reducing the likelihood of bugs from porting the XAML. Figure 2 shows some basic controls.

Figure 2 Basic Windows Phone 8 and Windows 8 Controls

Windows Phone 8 Windows 8
PhoneApplicationPage control is the root page element Page control is the root page element
Use the LongListSelector control to show vertically scrolling content Use the GridView control to show vertically scrolling content
Use the Pivot control for paging content horizontally Use the SemanticZoom control for grouping many items into grouped segments (it’s also possible to use the Grouped Items Page control)
Use the ApplicationBar control Use the AppBar control

The Windows 8 Visual Studio templates create a LayoutAwarePage, which is a subclass of the Page in the raw API, providing the following additional features and ensuring consistency of design and UX:

  • Application view state to visual state mapping
  • GoBack, GoForward and GoHome event handlers
  • Mouse and keyboard shortcuts for navigation
  • State management for navigation and process lifetime management
  • A default view model

Data Model and Supporting Code

All applications have to manage data, and data models provide the best way for doing so. They help ensure higher maintainability, modularity, project organization, and portability, and the APIs that support them are good candidates for code reuse. Still, you shouldn’t sacrifice application architecture or maintainability for code reuse. Shared libraries, code-sharing techniques and patterns such as Model-View-ViewModel (MVVM) will likely serve you better. For more information on these, see Doug Holland’s June issue article, “Code-Sharing Strategies for Windows Store and Windows Phone Apps” (msdn.microsoft.com/magazine/dn201744).

Platform-Specific Features

There are many features that behave similarly in both Windows 8 and Windows Phone 8 but are implemented differently. Because of this, you should avoid reusing code across platforms for certain processes and features, including:

  • Application Lifecycle
  • System Tasks and Contracts
  • Tiles
  • Toast Notifications
  • Local Storage
  • Networking
  • Background Processing
  • Camera
  • App Bar

Application Lifecycle Although there are strong parallels between the application lifecycle on Windows Phone 8 and on Windows 8, the two platforms have different APIs. As you can see in Figure 3, the high-level program states and flow between states are similar on both platforms, but resources on Windows Phone 8 are far more constrained, which is the reason for most of the differences in the lifecycle. On both platforms, only the foreground app can consume CPU resources (except for background tasks, which are managed by the OS).

Windows Phone 8 and Windows 8 Lifecycles
Figure 3 Windows Phone 8 and Windows 8 Lifecycles

Figure 4 shows differences in lifecycle behavior between the two platforms.

Figure 4 Differences in Windows Phone 8 and Windows 8 Lifecycles

Windows Phone 8 Windows 8
Windows Phone 8 apps are always launched or relaunched. Windows Store apps are resumed without page navigation.
Windows Phone 8 may tombstone apps. Windows 8 either suspends or completely terminates apps. Windows Store apps can support hosted-view activation, in which the app performs a single task inside a system-provided UI.
Windows Phone 8 supports Fast Application Resume. Windows 8 has no need for the Fast Application Resume feature because apps are kept in a suspended state for as long as possible; otherwise, they’re terminated.

Figure 5 shows the namespaces where application lifecycle events are found.

Figure 5 Application Lifecycle Namespaces

Windows Phone 8 Windows 8
Derive from: System.Windows.Application Derive from: Windows.UI.Xaml.Application
Application_Launching  
Application_Activated OnLaunched
Application_Deactivated OnSuspending
Application_Closing  

There are several app entry points on each platform, as Figure 6 shows.

Figure 6 App Entry Points

Windows Phone 8 Windows 8 Both
Speech launch Search App tile
App Connect Share Secondary tiles
    Toasts
    Protocol and file association

System Tasks and Contracts Both Windows 8 and Windows Phone 8 have built-in support for common operations that involve coordinating with the OS. Windows 8 handles these using contracts, while Windows Phone 8 uses tasks (such as Launchers and Choosers). Contracts and tasks provide similar capabilities to the user, but development is different. The functionality they each expose doesn’t necessarily map one-to-one, so you need to carefully consider tasks and contracts when porting an app.

Windows Phone 8 task APIs are found in the Microsoft.Phone.Tasks namespace: PhotoChooserTask, EmailAddressChooseTask, SaveContractTask and so on. In contrast, Windows 8 contracts have individual APIs related to the panes opened by charms (search pane, share pane and the like); support for contracts is declared in the application manifest. Contracts are essentially agreements and implementing them involves overriding methods in the Application class or handling events from classes in the Windows API.

Tiles Tiles are entry points for Windows Store and Windows Phone 8 apps. Primary tiles simply launch apps, while secondary tiles can be pinned to the Start screen; they’re effectively a “deep link” that can take the user to a specific page in the app. Both platforms support live tiles, in which content is periodically updated, but the APIs are completely different. Figure 7 describes Windows Phone 8 and Windows 8 tiles.

Figure 7 Comparison of Windows Phone 8 and Windows 8 Tiles

Windows Phone 8 Tiles Windows 8 Tiles
Three sizes: small, medium, wide Two sizes: smaller, larger
Standard tiles, flip tiles, cyclic tiles and iconic tiles (Microsoft.Phone.Shell) SecondaryTile can be customized using XML templates (Windows.UI.StartScreen)
Provide tile images in the manifest Provide tile images in the manifest
Create secondary tiles using the static method ShellTile.Create Create secondary tiles using the SecondaryTile.Re­­­questCreateAsync method
Update app tile using ShellTile.Update (Microsoft.Phone.Shell); push notification using ShellTileSchedule (ShellTileToast also updates tiles) Update app tile using TileUpdateManager and TileNotification (Windows.UI.Notifications)
User can unpin the app tile User can turn off the live tile

Figure 8A and Figure 8B show a code comparison of secondary tile creation. On Windows Phone 8, the ShellTile class provides a static interface for creating (and removing) secondary tiles. You can provide this using one of several classes that encapsulate a tile’s data: StandardTile, CycleTileData, FlipTileData or IconicTileData. Windows 8 has only one data structure to define a secondary tile (SecondaryTile). Tile creation is done with an asynchronous request, which asks the user if he would like to pin the tile to the Start screen.

Figure 8A Tile Creation in Windows Phone 8

CycleTileData tileData = new CycleTileData()
{
  Title = item.Title,
  SmallBackgroundImage = new Uri(item.GetImageUri(),
    UriKind.RelativeOrAbsolute),
  CycleImages = list
};
ShellTile.Create(new Uri(navDataSource,  
  UriKind.Relative), tileData, true);

Figure 8B Tile Creation in Windows 8

var tile = new SecondaryTile(
  item.UniqueId,      // Tile ID
  item.ShortTitle,    // Tile short name
  item.Title,         // Tile display name
  item.UniqueId,      // Activation argument
  TileOptions.ShowNameOnLogo, // Tile options
  uri                 // Tile logo URI
  );
await tile.RequestCreateAsync();

Toast Notifications Windows 8 toast notifications are similar to Windows Phone 8 reminders and alarms. They let an app notify the user of an event at a given time. Clicking a toast notification launches the app if it’s closed and resumes the app if it’s suspended.

Windows Phone 8 supports two types of notifications: alarm and reminder. It can also display toasts (even from the background) using ShellToast. Alarms and reminders are found in Micro­soft.Phone.Scheduler, while ShellToast is in Microsoft.Phone.Shell.

Windows 8 uses toast notifications via ToastNotification­Manager and ScheduledToastNotification, which are found in the Windows.UI.Notifications namespace and are enabled via the application manifest.

Local Storage The Windows.Storage namespace provides a new set of shared APIs that let applications handle local file management. On Windows Phone 8, System.IO.IsolatedStorage.IsolatedStorageFile provides backward compatibility with earlier Windows Phone versions, but you should move toward using the new APIs. You can use serialization and Windows.Storage.ApplicationData.Current.LocalFolder to persist app data to local app storage.

Both platforms support storage of key/value pairs (settings), and files and folders. However, Windows Phone 8 APIs are a subset of the full APIs and don’t provide support for the roaming data store, the temporary data store, local settings or roaming settings. Figure 9 is a summary of storage options for each platform.

Figure 9 Storage Options in Windows Phone 8 and Windows 8

Feature and Namespace Purpose Windows Phone 8 Windows 8
Windows.Storage Local app file storage Yes Yes
System.IO.IsolatedStorage.Isolated­StorageFile Local app file storage Yes No
ApplicationData settings (LocalFolder) Key/value storage No Yes
System.IO.IsolatedStorage.IsolatedStorageSettings Key/value storage Yes No
SQL CE Database Yes No

Networking Most applications rely heavily on the Internet capabilities of the devices they reside on to function properly. For both Windows 8 and Windows Phone 8, this capability is declared in the manifest. Figure 10 shows the relevant networking APIs.

Figure 10 Networking API Differences in Windows Phone 8 and Windows 8

Windows Phone 8 Windows 8 Both

ConnectionManager

  • System.Net

NetworkInterface

  • System.Net.Net­work­Information

HttpWebRequest, HttpWebResponse

  • System.Net

DatagramSocket, StreamSocket

  • Windows.Networking.Sockets

Socket (TCP or UDP), StreamSocket

  • System.Net.Sockets
 

HttpClient

  • System.Net.Http

WebClient

  • System.Net
 

Windows 8 introduces HttpClient, which acts as session to send requests to a server (HTTP, GET, POST and PUT). Each instance of HttpClient has its own connection pool to avoid interference from others. Data is returned as a string, HttpRequestMessage, stream or byte array. 

WebClient, on the other hand, is not available in Windows 8 (except for desktop apps). It’s used in Windows Phone 8 apps and its implementation is slightly different from the WebClient in earlier versions of Windows. In Windows Phone 8, you can also use HttpWebRequest/HttpWebResponse with an async wrapper. A release preview of a portable HttpClient is now available for both platforms. You can get this preview from the NuGet Gallery.

Background Processing In some situations you might want to run code in the background: Streaming music, pinging a server for updates, downloading a file and so on. Both platforms can give the OS a task to be run when some trigger occurs. These tasks are independent from the app and the OS has complete control over them.

There can only be one background agent per application, but that agent can run one or both of these tasks:

  • Periodic tasks: short tasks that the OS might run every 30 minutes.
  • Resource-intensive tasks: longer tasks that run when the phone is plugged in or has ample battery life.

Figure 11 shows what you need in order to implement background tasks on both platforms. Note that Windows Store apps that use background tasks must declare this in the app manifest.

Figure 11 Using Background Tasks in Windows Phone 8 vs. Windows 8

Windows Phone 8 Windows 8

Derive from BackgroundAgent or one of its subclasses:

  • Microsoft.Phone and Microsoft.Phone.Scheduler namespaces
Windows.ApplicationModel.Background
Override the OnInvoke method and call NotifyComplete when finished Implement the IBackgroundTask interface and its Run method
Check that the task is not already registered Declare background tasks in the manifest; check that the task isn’t already registered
Use ScheduledActionService to add and remove background agents Use BackgroundTaskBuilder to create and register an instance of your task
  Handle the BackgroundTask­Completed event to get data back from the task

Now I’ll demonstrate how to implement a background task, first in Windows 8 and then in Windows Phone 8.

Here are the high-level steps for Windows 8:

  • Implement IBackgroundTask interface and Run method
  • Declare background task use in the manifest
  • Check that the task is not already registered
  • Use BackgroundTaskBuilder to create and register a task instance
  • Handle the BackgroundTaskCompleted event to get data from task:
using Windows.ApplicationModel.Background;
namespace MyTaskExample
{
  public class SimpleBackgroundTask : IBackgroundTask
  {
    public void Run(IBackGroundTaskInstance task)
    {
      // Do stuff ...
    }
  }
}
  • Declare that the app uses a background task:
<Extensions>
  <Extension Category="windows.backgroundTasks"
    EntryPoint="Tasks.MyTask">
    <BackgroundTasks>
      <Task Type="systemEvent" />
    </BackgroundTasks>
  </Extension>
</Extensions>
  • And check the registration:
foreach (var task in Background.BackgroundTaskRegistration.AllTasks)
{
  // Use if (task.Value.Name == taskName) to see if
  // the task has already been registered
}
// If not ...
var taskBuilder = new BackgroundTaskBuilder();
taskBuilder.Name = taskName;
taskBuilder.TaskEntryPoint = "Tasks.MyTask";
taskBuilder.SetTrigger(
  new SystemTrigger(SystemTriggerType.TimeZoneChange, false));
BackgroundTaskRegistration myTaskRegistration =
   taskBuilder.Register();

Here are the high-level steps for Windows Phone 8:

  • Create ScheduledTaskAgent (Windows Phone Scheduled Task Agent template):
public class ScheduledAgent : ScheduledTaskAgent
{
  protected override void OnInvoke(ScheduledTask task)
  {
    // Write code here to perform task ...
    NotifyComplete();
  }
}
  • Check that task has already been scheduled to run, and if not, create a new one; otherwise, remove the existing task (the task scheduled to run periodically for 10 days):
PeriodicTask task =
     ScheduledActionService.Find(taskName) as PeriodicTask;
   bool found = (task != null);
   if (!found)            
     task = new PeriodicTask(taskName);
   else
     ScheduledActionService.Remove(taskName);
   task.Description = description;
   task.ExpirationTime = DateTime.Now.AddDays(10);
   ScheduledActionService.Add(task);

Unlike with Windows 8, there’s no need to declare support for background tasks in the manifest.

Camera Both Windows Phone 8 and Windows 8 support capturing images and videos but, as with other features, the APIs are different.

Capturing photos on Windows Phone 8 is a task handled by the OS. You can register a callback to handle the result when the user exits the camera UI. You may or may not have a photo as a result, so check before using the result. Video recording is not built-in to the camera-capture task, so it requires more work.

Unique to Windows Phone 8 is the ability to create a camera app called lens. You can also create rich media lenses, which provide a unique experience for viewing or editing photos. Moreover, the camera can be used as a gateway to other experiences. For instance, barcode-reader apps use the camera to scan a barcode and then display its associated data. All these lens apps are possible using lens extensibility, which allows launching directly from the lens picker into a viewfinder experience. You can also use special APIs to programmatically access the camera sensor. For more info, see “Lens extensibility for Windows Phone 8” (aka.ms/Vdgk8e) and “Capturing photos for Windows Phone” (aka.ms/Owcwpl) in the Windows Phone Dev Center.

Windows 8 uses the CameraCaptureUI (Windows.Media.Capture) for photos and videos. This requires enabling Webcam and Microphone in the manifest:

private async void OnCapturePhoto(object sender,
   TappedRoutedEventArgs e)
{
  var camera = new CameraCaptureUI();
  var file = 
    await camera.CaptureFileAsync(CameraCaptureUIMode.Photo);
  if (file != null)
  {
      // Do something with the result ...
  }
}

Windows Phone 8 uses CameraCaptureTask (Microsoft.Phone.Tasks) to take photos. This requires enabling ID_CAP_ISV_CAMERA and ID_CAP_MICROPHONE in the manifest, as shown in Figure 12.

Figure 12 Enabling ID_CAP_ISV_CAMERA and ID_CAP_MICROPHONE in the Windows Phone 8 Manifest

private readonly CameraCaptureTask cameraTask;
public Init() {
  cameraTask = new CameraCaptureTask();
  cameraTask.Completed += PhotoCaptured;
}
public void TakePhoto() {
  cameraTask.Show();
}
private async void PhotoCaptured (object sender,
   PhotoResult result) {
  await Task.Run(() => {
    // Do something with the result...
  });
}

App Bar Windows 8 app bars are much more powerful than Windows Phone 8 app bars. Commonly used actions—such as adding, editing and deleting items—can be placed on an app bar. An app can be notified when the user opens or closes an app bar by handling the Opened and Closed events.

There are significant differences in how the app bar works for each platform, as shown in Figure 13.

Figure 13 Differences in How the App Bar Works in Windows Phone 8 and Windows 8

Windows Phone 8 Windows 8
One app bar at the bottom of the page Two app bars: one at the bottom and one at the top

Only four items allowed

  • Put additional items on the menu
  • No grouping

Behaves like any container

  • No menu
  • Can group items in nested containers
ApplicationBar control inside PhoneApplicationPage.ApplicationBar AppBar control inside Page.BottomAppBar or Page.TopAppBar
Set Mode to Default to show the app bar when the page loads Set IsOpen to true to show the app bar when the page loads
Set IsMenuEnabled to enable the menu Set IsSticky to true to force an app bar to always remain open

The app bar declaration in Windows 8 is shown in Figure 14. Notice that two stack panels are used to group the buttons, with one group on the left and the other on the right.

Figure 14 The App Bar Declaration in Windows 8

<Page.BottomAppBar IsOpen="True">
  <AppBar x:Name="bottomAppBar" Opened="AppBar_Opened" 
        Padding="10,0,10,0">
    <Grid>
      <StackPanel Orientation="Horizontal" 
        HorizontalAlignment="Left">
        <Button Style="{StaticResource TakePictureAppBarButtonStyle}"
          Click="TakePicture_Click"/>
        <Button Style="{StaticResource ShareTaskAppBarButtonStyle}"
          Click="ShareImage_Click"/>
      </StackPanel>
      <StackPanel Orientation="Horizontal" 
        HorizontalAlignment="Right">
        <Button Style="{StaticResource StartCoookingAppBarButtonStyle}"
          Click="StartCooking_Click"/>
        <Button Style="{StaticResource PinToStartAppBarButtonStyle}"
          Click="PinToStart_Click"/>
      </StackPanel>
    </Grid>
  </AppBar>
</Page.BottomAppBar>

Figure 15 shows the app bar declaration in Windows Phone 8 (note that only four ApplicationBarIconButton elements are allowed on the phone ApplicationBar, and no containers are placed within the ApplicationBar element).

Figure 15 The App Bar Declaration in Windows Phone 8

<phone:PhoneApplicationPage.ApplicationBar x:name="ddd">
  <shell:ApplicationBar x:Name="bottomAppBar" IsVisible="True"
    IsMenuEnabled="True"  Mode="Default" Opacity="1.0">
    <shell:ApplicationBarIconButton x:Name="btnTakePicture"
      IconUri="/Assets/Icons/camera.png" 
      Click="btnTakePicture_Click" 
      Text="Take Picture"/>
    <shell:ApplicationBarIconButton x:Name="btnShareTask"
      IconUri="/Assets/Icons/share.png" 
      Click="btnShareShareTask_Click" 
      Text="Share Image"/>
    <shell:ApplicationBarIconButton x:Name="btnStartCooking"
      IconUri="/Assets/Icons/alarm.png" 
      Click="btnStartCooking_Click" 
      Text="Start Cooking"/>
    <shell:ApplicationBarIconButton x:Name="btnPinToStart"
      IconUri="/Assets/Icons/like.png" 
      Click="btnPinToStart_Click" 
      Text="Pin To Start"/>
  </shell:ApplicationBar>
</phone:PhoneApplicationPage.ApplicationBar>

Wrapping Up

Increasingly, consumers expect continuity of experience between their smartphones and other devices. The Windows 8 and Windows Phone 8 common core allows for a reasonable level of reuse when building solutions for both platforms. However, as you’ve seen in this article, it’s important to recognize the major differences in the physical devices and the way in which users interact with them, as well as the differences in the APIs for each. These differences mean application designers must account for building a separate UI and UX, which in turn means little or no reuse of XAML across the platforms. Although some APIs are available for both platforms, as with Windows.Store.StorageFile, many features are externally similar but implemented differently. That’s the case for lifecycle events, tiles, media capture, tasks and contracts, settings, background tasks, and the app bar.

Once you grasp these differences, you can confidently exploit cross-platform code-reuse techniques such as Portable Class Libraries, runtime components and so forth. To learn more about these techniques, please refer to Doug Holland’s code-sharing article I mentioned earlier, as well as to the Windows Phone Dev Center article at aka.ms/sharecode. And you’ll want to download the sample code showing sharing in action from aka.ms/gxcvq3.


Joel Reyes is a technology evangelist in DPE Public Sector focused on Windows Phone 8 and Windows 8. You can reach him at joel.reyes@microsoft.com.

Thanks to the following technical experts for reviewing this article: Andrew Byrne (Microsoft) and Matthias Shapiro (Microsoft)