(X) Hide this
    • Login
    • Join
      • Generate New Image
        By clicking 'Register' you accept the terms of use .

Windows Phone 8: Protocol and File Type Associations

(2 votes)
Peter Kuhn
>
Peter Kuhn
Joined Jan 05, 2011
Articles:   44
Comments:   29
More Articles
1 comments   /   posted on Jan 30, 2013
Categories:   Windows Phone
Tweet

In Windows Phone 7 we had several options to communicate with the outside world, for example using Web Services, HTTP or low-level communication using sockets. This already enabled a large field of possibilities for interesting apps. For example, I built a remote controlling component named PAARC [1] on top of this to virtually communicate with and control any .NET application from your phone. However, despite these options support for a lot of alternate technologies was missing: app developers could not use well-established things like Bluetooth, support for new technologies like NFC was missing completely on the phones, and direct app-to-app communication on a single device was impossible. Windows Phone 8 improves all of these situations, and over the next three articles I'll take a deeper look at some of the new possibilities that have been added. This time, I'll concentrate on what options we have to enable a greater interaction between apps on the local device.

The Fundamental Problem

Apart from the fact that no APIs existed for it, direct app-to-app communication on Windows Phone 7 was impossible because the technical specification of the platform indirectly prevented it: there is no multi-tasking for third-party apps on Windows Phone 7. So simply because no two apps can run simultaneously it's not possible to establish direct communication between them. Let's put it out straight right in the beginning: this particular situation has not changed in Windows Phone 8. Your apps still get tombstoned, and no general purpose multi-tasking has been introduced. Yes, we do have some scenarios where apps can continue to run in the background (for example location tracking or VoIP apps), but even those very specialized apps have no access to APIs for direct, bi-directional communication with other apps.

What We Can Do

So what new ways of doing this do we have? The answer is: protocols and file type associations. The idea is to enable apps to indirectly interact with other apps on the same device by passing around small bits of information in some style of one-way communication. The involved concept really is nothing new and has existed on desktop systems in a very similar flavor for decades, so let's look at two simple examples to make this abstract description more understandable quickly:

Protocols Explained

Let's assume you receive an email from a friend in your favorite email client, for example Outlook. Your friend sends you a link to a cool web site he discovered in that email. When you click that link, what happens? Your web browser opens and loads the corresponding web site that the link points to. How does this work? Well, the web browser has registered with the operating system for a certain protocol, in this case HTTP(S), in the past (this is what happens behind the scene when a browser asks you whether it should become your default browser!). So when you click a hyperlink in an email, Outlook says "I don't know what to do with this, let's hand it over to the operating system". The operating system looks up if there's an application registered for the protocol the hyperlink is using, and then simply passes on the information (the web site the hyperlink points to) to that registered application, in this case let's say Internet Explorer. The following diagram shows this in more detail:

What is the benefit of such a setup?

  • Outlook can communicate with Internet Explorer indirectly, passing on all the required information to it.
  • Outlook doesn't need to know how to do this, it simply lets the operating system do the heavy lifting.
  • This system is extremely flexible. In fact, Outlook doesn't even know about Internet Explorer. If it's e.g. Chrome that has registered the protocol, the operating system will pass on the information to Chrome.

So, for developers it's extremely simple to pass on information to other applications, because it always works in the exact same way and there's no need to e.g. learn the specific API of a specific application. You only need to know about the kind of data to send. On the other hand, developers also can register their own applications for protocols easily and by that integrate deeply into the operating system logic with little effort. And above all we have the user who is able to decide extremely flexibly who should handle which protocol, and it will all continue to work when they switch between different applications. Other URI samples for protocols are "mailto://" to launch your mail client or "skype://" to initiate a, well, Skype call.

File Associations Explained

In the very same way protocols work, applications can register for file extensions with the operating system as well. Let's return to the previous sample and say your friend sent you an email that contains a ZIP file attachment. When you click on that attachment, Outlook now says "I don't know what to do with this file, so let's hand it over to the operating system". The operating system in turn looks up the registration for the file extension of the attachment and then decides that it should pass the file on to e.g. 7-zip, which then knows how to open and extract the archive.

As you can see, the concept is the same as with protocols, but now we're dealing with file information instead of URIs that are passed around. Other samples for file associations are viewers that register for .PDF files or video players that register for .MP4 file extensions.

All in all, dozens and dozens of registered file type associations and protocols create a very complex and highly dynamic network of indirect application relationships that can indeed look differently for each and every computer and user.

How It Works on Windows Phone

The concept of all this is virtually the same on Windows Phone 8, however there are two significant differences:

  1. The involved technical details obviously are different from what you may know from desktop systems. For example, instead of registering with the registry, the application manifest is used, and to trigger the operating system to invoke other apps you use the well-known platform concept of launchers.
  2. Certain limitations and restrictions apply. For example, Microsoft wants to make sure that the core user experience of the system stays consistent, and of course also that malicious apps cannot take over that core functionality. This means that you e.g. cannot register protocols that the system has already registered, and the same is true for file type associations. The drawback of this is that e.g. you cannot create a custom sound player that handles MP3 files globally.

Let's dive into some samples now.

Registering for Protocols and File Type Associations

If you want to configure your app to handle a certain file extension or protocol, all you have to do is add the corresponding entries to an "Extensions" section (directly below the "Tokens" element) in the WMAppManifest.xml file of your project, like this:

   1: <Extensions>
   2:   <FileTypeAssociation Name="My File Type"
   3:                        NavUriFragment="fileToken=%s"
   4:                        TaskID="_default">
   5:     <Logos>
   6:       <Logo Size="small"
   7:             IsRelative="true">Assets/myFileType_33x33.png</Logo>
   8:       <Logo Size="medium"
   9:             IsRelative="true">Assets/myFileType_69x69.png</Logo>
  10:       <Logo Size="large"
  11:             IsRelative="true">Assets/myFileType_176x176.png</Logo>
  12:     </Logos>
  13:     <SupportedFileTypes>
  14:       <FileType>.myFileType</FileType>
  15:     </SupportedFileTypes>
  16:   </FileTypeAssociation>
  17:   <Protocol Name="myprotocol"
  18:             NavUriFragment="encodedLaunchUri=%s"
  19:             TaskID="_default" />
  20: </Extensions>

Registering a protocol is easy: really all you have to define is the "Name" part of the element. This determines what is used as the protocol part of URIs. In the above sample, the "Name" attribute is set to "myprotocol", so corresponding URIs that will be matched to your app will look like "myprotocol:[additional content that is sent to your app]". The format and details of the additional content is up to you to define. The other information ("NavUriFragment" and "TaskID") must have the exact values shown here.

For file type associations you need to provide both a (descriptive) name as well as a list of supported file types that contains at least one entry (maximum is 20 by the way). Here you can specify which file extensions your application should be invoked for. Please note that the extension definition must include the dot. Optionally you can use the "Logos" element to provide icons that are used when files of your file type are displayed in other apps, for example in the web browser or email app. Again, most of the attribute values have to have the exact values shown here to work, like the "NavUriFragment" that needs to be set to "fileToken=%s".

More information on setting up your application for protocols and file types can be found on MSDN [2]. As mentioned above, you cannot register all protocols and file types at will; a lot of them are reserved by the operating system. A list of these can also be found on MSDN [3].

Receiving Data

Receiving data works similarly for both scenarios: the user taps on a link containing your registered protocol or a file with your registered file extension, and the operating system will launch your app, passing on the required data. To process that data, you need to set up a URI mapper in your app and handle what is passed on. Here is a sample snippet for this:

   1: internal class CustomUriMapper : UriMapperBase
   2: {
   3:     public override Uri MapUri(Uri uri)
   4:     {
   5:         var tempUri = HttpUtility.UrlDecode(uri.ToString());
   6:  
   7:         if (tempUri.Contains("myprotocol:"))
   8:         {
   9:             // app was launched using our protocol
  10:             // extract additional information
  11:             var parameters = ExtractUriParameters(tempUri);
  12:  
  13:             // pass data on to a page in the app
  14:             return new Uri("/MainPage.xaml?Data=" + parameters, UriKind.Relative);
  15:         }
  16:         if (tempUri.Contains("FileTypeAssociation"))
  17:         {
  18:             // a file token has been passed on to the app
  19:             // extract file id
  20:             var fileIdIndex = tempUri.IndexOf("fileToken=") + 10;
  21:             var fileId = tempUri.Substring(fileIdIndex);
  22:  
  23:             // open another page in the app
  24:             return new Uri("/HandleFile.xaml?FileToken=" + fileId);
  25:         }
  26:         else
  27:         {
  28:             // normal app launch, simply pass through the uri
  29:             return uri;
  30:         }
  31:     }
  32:  
  33:     // additional methods
  34: }

As you can see, the sample distinguishes between three situations. First of all there's the trivial case of a normal app launch that simply passes on the received URI (typically this will point to your app's entry page). If however the app is launched using a link with the registered protocol, you need to extract the data from the URI and make something meaningful out of it. You can for example then decide what sub page you want to launch, depending on that information.

When the application is launched as a result of a file type association, things become a bit more complex. The sample shows how to extract the file Id from the URI and pass it on to a separate page of the application. This Id can then be used in conjunction with the new SharedStorageAccessManager class [3] for further processing. It's important to realize that you are not able to directly modify files that have been passed on to your app this way. This means that your app can never get direct access to an attachment that resides in the email client, for example. Instead, to do something meaningful with that file, you need to copy it to your own app's storage first, using the said shared storage access manager [4].

To actually use this URI mapper in your application you need to set the corresponding property on the root frame. For the default templates, a good place would be the "InitializePhoneApplication" method in App.xaml.cs:

 

Launching Other Apps

To launch other apps and pass on custom data or files to them, you simply use the new Launcher class [5] that provides methods for both using a file or a URI. Here's a snippet for using a URI:

   1: private async void LaunchApp(string data)
   2: {
   3:     var uri = new Uri(string.Format("myprotocol:{0}", data));
   4:     var success = await Launcher.LaunchUriAsync(uri);
   5: }

Note that you can check the return value to see if launching the URI actually was successful or not. In the same way you can launch another app by file extension when you use the corresponding method. You obviously have to pass on a StorageFile instance for that:

   1: private async void LaunchApp(StorageFile file)
   2: {
   3:     var success = await Launcher.LaunchFileAsync(file);
   4: }

Not only third-party apps use this mechanism. In my last article on the new live tile and lock screen features [6] I demonstrated how the Launcher class can be used to navigate the user to built-in screens of the operating system itself. I used a URI of "ms-settings-lock:" to open the settings app with the lock screen options.

Of course, launching other apps does not only work programmatically. If for example the user taps a link or file on a web site, the email client or other areas of the phone, registered apps will be launched in a similar way, just as explained in the initial part of this article.

Additional Notes

There are some additional details worth mentioning. For example, when a user wants to open a file or launch an app using a protocol but does not have a suitable app for it installed, Windows Phone will go out to the store and retrieve a list of applications that can handle the request. The user then can choose whether they want to install any of the available apps. When you submit an app to the Windows Phone Store that registers for a protocol or file type, it will be automatically added as an option to that list. That's pretty comfortable for users and also convenient for developers.

Another thing is that if the user has installed multiple apps that can handle the same protocol or file extension, they will be presented with a list of these installed apps and then can choose which one to use as target when they e.g. click on a corresponding link or file. So multiple applications acting as similar targets can co-exist on the same device. One drawback is that once multiple apps for the same file type are installed, your logos (see above) won't show up anymore (how should the operating system decide which logo to show?).

Conclusion

Registering for protocols and file types is not exactly highly sophisticated or even duplex app-to-app communication. However it enables a whole lot of new scenarios for app developers and finally provides the possibility to deeply integrate with the system and provide even more comfortable features to the user.


Subscribe

Comments

  • MarcoBet

    Re: Windows Phone 8: Protocol and File Type Associations


    posted by MarcoBet on Apr 02, 2015 05:27
    I like the valuable info you provide in your articles. I’ll bookmark your weblog and check again here regularly. I’m quite sure I’ll learn many new stuff right here! Good luck for the next!
    • Cipto Junaedy
    • Cipto Junaedy
    • Cipto Junaedy
    • Jadwal MotoGP 2015 di Trans 7
    • Cara Upload Video ke Youtube
    • Download BBM Untuk Android Versi Terbaru
    • Cara Membuat Email
    • Cara Instal Windows 7
    • Jinpoker.com Agen Judi Poker Online dan Domino Online Indonesia Terpercaya
    • Cahayapoker.com Agen Judi Poker Dan Domino Uang Asli Online Terpercaya Indonesia
    • ituDewa.net Agen Judi Poker Domino QQ Ceme Online Indonesia
    • Nusantarapoker.com Agen Texas Poker Dan Domino Online Tanpa Robot Terpercaya

Add Comment

Login to comment:
  *      *       

From this series