Windows Phone 7 Quick Tutorials: Part 6 - Launchers and Choosers

In this sixth article of the WP7 Silverlight series I will discuss the launcher and chooser APIs that enable WP applications to provide common tasks to the users, such as making phone calls, browsing the web or taking pictures.

WP7 applications run isolated in a sandbox; they do not have access to stores such as the contacts list, nor can they directly invoke applications such as the phone or e-mail. To allow applications to perform such tasks, Windows Phone provides two sets of APIs, called Launchers and Choosers.

Launchers

Launchers are APIs that allow applications to do common tasks such as making a phone call, sending an SMS or browsing the web. When a launcher is called, the application is tombstoned. After the launcher terminates, the application is activated again. Launchers to not return any data to the calling application.

The following launchers are available in the Microsoft.Phone.Tasks namespace from the Microsoft.Phone assembly:

  • EmailComposerTask: launches the Email application and displays a new email message
  • MarketplaceDetailTask: launches the Windows Phone Marketplace client application which then shows the details page for a product specified by the unique identifier you provide.
  • MarketplaceHubTask: launches the Windows Phone Marketplace client application.
  • MarketplaceReviewTask: launches the Windows Phone Marketplace client application which then displays the review page for your application.
  • MarketplaceSearchTask: launches the Windows Phone Marketplace client application which then shows the search results based on search terms you provide.
  • MediaPlayerLauncher: launches the Media Player application and plays the media file you specify.
  • PhoneCallTask: launches the Phone application and displays the specified phone number and display name.
  • SearchTask: launches the Search application and performs search query you provide.
  • SmsComposerTask: launches the Messaging application which displays a new SMS message.
  • WebBrowserTask: launches the Web browser and displays the URL you provide.

Let's see a couple of examples for using launchers. I'll create a single page Silverlight application with two buttons: "Make Call" and "Visit my blog".

The first button will open the Phone application displaying the John Doe name and phone number 1234567890. The code is as simple as this:

private void btnPhone_Click(object sender, RoutedEventArgs e)
{
   PhoneCallTask phoneCallTask = new PhoneCallTask();
   phoneCallTask.PhoneNumber = "1234567890";
   phoneCallTask.DisplayName = "John Doe";
   phoneCallTask.Show();
}

If you run the application you'll notice the phone call is not made until the user presses the "call" button in the Phone application. When the phone call ends, the launcher terminates and the application is re-activated. The image strip below shows several screen shots of the application and the launcher.

The second button will start the web browser and navigate to my blog, www.mariusbancila.ro/blog. The code, again, is very simple:

private void btnWeb_Click(object sender, RoutedEventArgs e)
{
   WebBrowserTask webBrowserTask = new WebBrowserTask();
   webBrowserTask.URL = "http://www.mariusbancila.ro/blog";
   webBrowserTask.Show();
}

The next image strip shows the application and the web browser after starting the launcher.

You can find examples for all the launchers in MSDN.

Windows Phone 7 Quick Tutorials: Part 6 - Launchers and Choosers

Choosers

Choosers are APIs similar to launchers; however they return a value to the calling application. They are enabling common tasks such as taking a photo or selecting a phone number from the contacts list. The following choosers are available:

  • CameraCaptureTask: launches the Camera application.
  • EmailAddressChooserTask: launches the Contacts application and allows the user to select a contact.
  • PhoneNumberChooserTask: launches the Contacts application and allows the user to select a contact.
  • PhotoChooserTask: launches the Photo Picker application.
  • SaveEmailAddressTask: saves the provided email address to the Contacts list.
  • SavePhotoNumberTask: saves the provided phone number to the Contacts list.

All these chooser classes are derived from the ChooserBase class. This is a generic class with the type argument representing the type of the event handler arguments for its single event called Completed. This event occurs when the chooser task is completed. You should handle this event to get the result from the chooser.

public event EventHandler<TTaskEventArgs> Completed;

Note: the SavePhotoNumberTask chooser does not return any data, but you can still handle the Completed event to check whether the task was successfully completed.

The next demo application shows how to use the camera to take pictures and then display them in your application in a list. If you're using the emulator you can still "take pictures", because the emulator simulates this action. It has a small application with a black rectangle moving across a white background. When you hit the button to capture the picture it saves the current image, and if you accept it, it returns the picture to your application.

The XAML code below shows the content panel with the list, whose items are composed of an image and a text block, and the application bar with a single button that starts the chooser.

<!--ContentPanel - place additional content here-->
<Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
    <ListBox x:Name="listPictures">
    <ListBox.ItemTemplate>
       <DataTemplate>
          <StackPanel Orientation="Horizontal">
             <Image Width="64" Margin="5,5,5,5" Source="{Binding Picture}" />
             <TextBlock Text="{Binding Caption}" Style="{StaticResource PhoneTextTitle2Style}" />
          </StackPanel>
       </DataTemplate>
    </ListBox.ItemTemplate>
 </ListBox>
</Grid>

<!--Sample code showing usage of ApplicationBar-->
<phone:PhoneApplicationPage.ApplicationBar>
    <shell:ApplicationBar IsVisible="True" IsMenuEnabled="True">
     <shell:ApplicationBarIconButton IconUri="/Images/appbar.feature.camera.rest.png" 
                                     Text="take picture"
                                     x:Name="btnCamera"
                                     Click="btnCamera_Click"/>
    </shell:ApplicationBar>
</phone:PhoneApplicationPage.ApplicationBar>

The view model user for the list items looks like this:

public class ListboxItemViewModel : INotifyPropertyChanged
{
  private string _Caption;
  public string Caption
  {
     get
     {
        return _Caption;
     }
     set
     {
        if (value != _Caption)
        {
           _Caption = value;
           NotifyPropertyChanged("Caption");
        }
     }
  }

  private BitmapImage _Picture;
  public BitmapImage Picture
  {
     get
     {
        return _Picture;
     }
     set
     {
        if (value != _Picture)
        {
           _Picture = value;
           NotifyPropertyChanged("Picture");
        }
     }
  }

  public event PropertyChangedEventHandler PropertyChanged;
  private void NotifyPropertyChanged(String propertyName)
  {
     PropertyChangedEventHandler handler = PropertyChanged;
     if (null != handler)
     {
        handler(this, new PropertyChangedEventArgs(propertyName));
     }
  }
}

What we have to do now is creating an instance of CameraCaptureTask and in the constructor add a handler for the Completed event. When the user presses the "take picture" app bar button, we start the chooser by calling Show(). In the handler for the Completed event, we check whether the task completed successfully, and if so we retrieve the bitmap image from the result stream and add a new item to the list.

public partial class MainPage : PhoneApplicationPage
{
  CameraCaptureTask m_cameratask = new CameraCaptureTask();
  int m_counter;

  public MainPage()
  {
     InitializeComponent();

     m_cameratask.Completed += new EventHandler<PhotoResult>(cameratask_Completed);
  }

  void cameratask_Completed(object sender, PhotoResult e)
  {
     if (e.TaskResult == TaskResult.OK)
     {
        BitmapImage bmp = new BitmapImage();
        bmp.SetSource(e.ChosenPhoto);

        listPictures.Items.Add(new ListboxItemViewModel()
        {
           Picture = bmp,
           Caption = String.Format("image{0:D3}", ++m_counter)
        });
     }
  }

  private void btnCamera_Click(object sender, EventArgs e)
  {
     m_cameratask.Show();
  }
}

Remember the application is tombstoned when a launcher or chooser starts and re-activated when it completes. The following handlers are called when you press the "take picture" button, take a picture and then return to the application (supposing you overrode OnNavigatedFrom and OnNavigatedTo for the main page): OnNavigatedFrom -> Application_Deactivated -> Application_Activated -> cameratask_Completed -> OnNavigatedTo.

The image strip below shows the application initially, then the Camera application that allows you to take a picture (unfortunately the black rectangle on the white background image is not visible in these shots) and then the application again after taking several pictures.

[wp7choosers_1.jpg]

You can read more and find examples for all the chooser tasks in MSDN.

Conclusions

Launchers and choosers are WP APIs that enable applications to perform common tasks such as making phone calls, sending SMS, talking pictures or opening a web page in the browser. Choosers only differ from launcher in the way they complete, because they return some data to the calling application. When a launcher or chooser is called, the application is tombstoned, and then re-activated again when launcher/chooser completes.



About the Author

Marius Bancila

Marius Bancila is a Microsoft MVP for VC++. He works as a software developer for a Norwegian-based company. He is mainly focused on building desktop applications with MFC and VC#. He keeps a blog at www.mariusbancila.ro/blog, focused on Windows programming. He is the co-founder of codexpert.ro, a community for Romanian C++/VC++ programmers.

Downloads

Comments

  • There are no comments yet. Be the first to comment!

Leave a Comment
  • Your email address will not be published. All fields are required.

Top White Papers and Webcasts

  • On-demand Event Event Date: September 10, 2014 Modern mobile applications connect systems-of-engagement (mobile apps) with systems-of-record (traditional IT) to deliver new and innovative business value. But the lifecycle for development of mobile apps is also new and different. Emerging trends in mobile development call for faster delivery of incremental features, coupled with feedback from the users of the app "in the wild." This loop of continuous delivery and continuous feedback is how the best mobile …

  • Packaged application development teams frequently operate with limited testing environments due to time and labor constraints. By virtualizing the entire application stack, packaged application development teams can deliver business results faster, at higher quality, and with lower risk.

Most Popular Programming Stories

More for Developers

Latest Developer Headlines

RSS Feeds