Pause/resume active music players

The current application certification requirements for Windows Phone define, in chapter 6.5, special criteria for applications which need to interrupt the ongoing audio playback (active music players or radio). This applies mainly to games when their background music track is intended to replace whatever is currently playing on the device.

The rules make sense and can be easily implemented, but the trick is in making sure that any currently playing track can be paused/restored, regardless of the source. The code snippet below shows how the Pause/Resume functionality can be implemented, although as you can see, the solution cannot guarantee the restore functionality.

First you need to add the namespaces for XNA and Radio to your code:

using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Media;
using Microsoft.Devices.Radio;

And of course the corresponding references to your project. Then in your class, just before playing/stopping your own audio playback, call the Pause and Resume methods implemented similar to the ones listed below:

	bool radioIsPaused = false;

        private void Pause(object sender, RoutedEventArgs e)
        {
            // stop the FM Radio if playing on Windows Phone 7
            try
            {
                FMRadio radio = Microsoft.Devices.Radio.FMRadio.Instance;
                if (radio.PowerMode == RadioPowerMode.On)
                {
                    radio.PowerMode = RadioPowerMode.Off;
                    radioIsPaused = true;
                }
            }
            catch (RadioDisabledException)
            {
                // radio not supported, move along
            }

            if(!radioIsPaused)
            {
                // Regular FrameworkDispatcher.Update calls are necessary for fire and forget
                // sound effects and framework events to function correctly. 
                // See http://go.microsoft.com/fwlink/?LinkId=193853 for details.
                FrameworkDispatcher.Update();

                // This should stop any 3rd party player
                // May briefly resume a paused XBox Music player
                MediaPlayer.Resume();

                // This will stop the XBox Music player
                MediaPlayer.Pause();                    
            }
        }

Note that MediaPlayer can only control the XBox Music player but attempting to resume playback on it will pre-empt the other active players (tested with Nokia Music and Podcatcher). If the XBox Music app is running in the background but the playback is already paused, the Resume call will activate it briefly before the subsequent Pause call sends it back to sleep.

For controlling the radio we use the FM Radio API being careful to handle the exception thrown on the smartphone models which do not support the radio feature.

Once we are ready to return the audio channel to the paused players:

        private void Resume(object sender, RoutedEventArgs e)
        {
            if (radioIsPaused)
            {
                try
                {
                    FMRadio radio = Microsoft.Devices.Radio.FMRadio.Instance;
                    if (radio.PowerMode == RadioPowerMode.Off)
                    {
                        radio.PowerMode = RadioPowerMode.On;
                        radioIsPaused = false;
                    }
                }
                catch (RadioDisabledException)
                {
#if DEBUG
                    // radio not supported, how was it paused?
                    throw;
#endif
                }
            }
            else
            {
                // This will resume the Xbox player
                MediaPlayer.Resume();

                // We cannot resume Nokia Music or 3rd party players
            }
        }

With this code and a couple of UI elements to satisfy the rest of the specific requirements you should be able to pass the certification testing without problems. Good luck!

Using the Windows Phone Runtime to mix C++ and C# code

In Windows Phone 7,  you will typically define your UI in XAML and write the code in C#. If you’re an advanced XAML coder, you might want to harness the power XAML bindings to limit the amount of code you’ll have to write, and define as much as possible in XAML. If you’re a game developer, you might opt for the XNA framework, in that case you UI will be written from scratch. In any case, regardless of the UI framework you decide to use, your business logic will be coded in C#.

The reason why C# is required comes from the constraint that in WP7, your application is confined run on top of the CLR (Common Language Runtime). The CLR concept is very similar to a Java virtual machine :  the code is converted to an intermediary language that the virtual machine will execute. The CLR environment is commonly called the “managed” mode. The managed mode comes with many great advantages, most notably garbage collection and reflection.  C# is a managed language.

That changed in Windows Phone 8! In addition to the managed framework, developers can write in “native” code. Native code, in comparison with managed code, does not run on top of a virtual machine, but is compiled directly into machine code. As you might expect, native code typically execute slightly faster than managed code. On WP8, native code is written in C or C++.

It is possible to glue pieces of native code with pieces of managed code, thanks to the Windows Phone Runtime framework. The framework takes care of the magic required to convert objects across managed and native runtimes. This Nokia developer wiki gives a quick tutorial how to get started with the Windows Phone Runtime, while this article C++ support from Windows Phone 8 goes into deeper details.

There are some limitations how one passes objects back and forth between managed and native runtimes, and while the “Windows Phone Runtime Component”  code template shipping with Visual Studio provides all the necessarily plumbing to call a Native object from a Managed object, it may not be that obvious how to call a managed object from a Native object. For example, when a developer needs to call from C++ the functionality only provided by  .NET, like modifying live tiles, send a SMS, … The same wiki article provides a solution for such a scenario.

Of course, it’s not because you can that you should!  Stick with C#, unless you really need that little extra speed improvement. Or if you have a C++ library that does a great job and just do not want to convert it to C#: that would be such a waste of your time.

 

 

Use the PeerFinder API to launch applications via NFC

With the introduction of NFC on Windows Phone 8, the scenarios of device interaction become much more reachable to consumers and developers. By simply by tapping one WP8 device with another, we can perform a variety of tasks, like sharing a contact, photo, video, or app, pairing with Bluetooth, etc.

The Proximity API in WP8 provides two main classes for NFC related features: ProximityDevice and PeerFinder. ProximityDevice enables functionality like publish/subscribe for NFC messages to and from tags or another devices, while PeerFinder focuses on pairing two devices with a socket connection using NFC tapping or browsing without NFC involvement.

Launching an application from another device is one of the most important features that NFC provides. In most cases, launching the same application from another device is desired to enable further interactions on the same app context between two devices, such as multi-player games, messaging apps, media sharing, etc. Both ProximityDevice and PeerFinder can perform this task.

By using ProximityDevice, developers need to make a URI association for the app and then publish the custom URI to another device. This approach enables the app to interact with other applications as well. However, sometimes app developers do not want to disclose the interface to others due to confidentiality. In such cases, the URI association might not be the best option.

On the other hand, many developers have encountered issues where if both apps are running in the foreground on separate devices and either Fast App Resume (FAR) or BackgroundExecution is defined in the manifest, then passing the URI through NFC will not trigger the MapUri function to launch the desired page in the application. In such cases, the PeerFinder approach to launch the same app on another device becomes more reliable option for developers.

So, how do you launch the same app on another device using PeerFinder? The solution is pretty simple. Developers just need to include the following code in their application. As it requires NFC to make tapping gesture work, the application needs to have ID_CAP_PROXIMITY and ID_REQ_NFC defined in the manifest.

...
PeerFinder.TriggeredConnectionStateChanged += PeerFinder_TriggeredConnectionStateChanged;
PeerFinder.Start();
...
void PeerFinder_TriggeredConnectionStateChanged(object sender, TriggeredConnectionStateChangedEventArgs args)
{
//to-do
}

After PeerFinder is started on device A, then when another device (“B”) enters into proximity range, device B will behave according to the following rules:

  • Case 1: If device A has the app but device B doesn’t, device B will get a prompt to search for the app in the store as in the first illustration.
  • Case 2: If both device A and B have the app installed and the app is not yet launched on B, then B will get a prompt to launch the app as in the second illustration.
  • Case 3: If both device A and B have the app installed and both have launched the same app, then TriggeredConnectionStateChanged will get notified and further actions can be performed.

App not installed    App not installed and not launched

If the app needs a socket connection for further action between two devices, then it can check the TriggeredConnectState property in the  TriggeredConnectionStateChangedEventArgs passed in with the  TriggeredConnectionStateChanged event. Once the state is changed to TriggeredConnectState.completed, then the Socket property under TriggeredConnectionStateChangedEventArgs will be ready to use.

Some developers want to distinguish between normal application launching and launching by PeerFinder. This can be achieved by using the URI mapper and checking the URI passed. In the PeerFinder case, the URI passed to the MapUri function will look like this:

/MainPage.xaml?ms_nfp_launchargs=Windows.Networking.Proximity.PeerFinder:StreamSocket

Launching the same app on another device using PeerFinder does not require URI association, which implies that no other application can pretend to be the application by associating the same URI theme. This ensures that only the expected app is launched. It also resolves the issue mentioned above in the FAR or BackgroundExecution case. However, if developers want to share their application experiences with other applications, then using ProximityDevice with URI association is the proper option to choose.

Touchy-Feely with DOM Events: Rethinking Cross-Device User Interaction

There have been numerous ways for users to interact with web pages on mobile phones. Historically, users navigated the mobile web by pressing physical buttons (arrow keys, soft keys, etc.), while some devices required a stylus.

In the last several years, devices with touch-enabled screens have been adopted at such a rapid rate that touch interaction has become ubiquitous. Now we have tablets that take input not only from touch, but from keyboards and mousepads using optional peripherals.

So what does it mean to you as a web developer? It means you need to detect the correct user input method, and design the correct user experience into your web apps.

Continue reading

How to use emulators to develop NFC features on WP8

One of the more interesting features of Windows Phone 8 is its Proximity Framework for Near-field communications (NFC). Both Nokia and Microsoft have heavily invested in this area. The Proximity API provides you the controls needed to innovate on NFC technology, but at the moment Windows Phone SDK default emulator does not simulate NFC. That means you have to use real WP8 devices to test and debug NFC-related features. If you’re developing a feature to be used between NFC-enabled devices, you’ll need to have at least two devices in hand. In addition, there are often physical movements required to perform NFC interactions while debugging.

Continue reading

Creating A Custom HTML5 Form Validation

In his blog post on HTML5 forms and IE10 Mobile, Andrea explained HTML5 forms and what is new in Internet Exporer 10 Mobile, so you should now have some understanding of HTML5 form validation. To summarize, HTML5 eases the pain of writing extra logic to validate users’ form inputs, letting you create usable forms with a little or no scripting.

In this tutorial, I will show you a practical example of creating a custom validated form  with CSS3, web fonts, and a bit of JavaScript (or not).
Continue reading

Measuring site performance with JavaScript on mobile

There is a lot of talk around responsive Web design being too slow or too resource intensive and that other methodologies can achieve better performance. I don’t want to go into the details of which approach is better because I think different scenarios require different solutions. What is certainly true in all cases is that a Web site or app that loads faster is better than one that is slow. Companies like Google, Gomez and Akamai have all published papers and survey results showing how speed affects user perception of a service from your desktop computer and even more on a mobile device (KISSmetrics has also drawn a nice infographic for the lazy ones). This is the first article and another one will follow shortly. Continue reading

HTML5 forms (and IE10 (Mobile))

One of the many improvements introduced by HTML5 is around forms, users hate filling forms and developers hate validating the data submitted. HTML5 makes these tasks a lot simpler.
In this article I will not talk about what HTML5 added, but I will rather focus on what is new in IE10 mobile, i.e. the browser that comes with Windows Phone 8. At the end of the article I have collected a few useful links that cover HTML5 forms at large and provide more examples and complete support tables. All the code examples are meant to be cross-browser, unless specified. Continue reading

Nfc Interactor + NDEF Library for Windows Phone 8

As one of the world’s first Windows Phone 8 applications, Nfc Interactor is now available for download in the Windows Phone Store.

This is an incredibly useful tool for developers, as it allows you to experiment with NFC on your phone, without the need to write your own code right away.

Nfc Tool for Developers

Nfc Interactor can read and parse NFC tag contents. Even better is that you can use it to easily create and write your own tags. This allows you to for example test how your WP8 app reacts to LaunchApp tags, or if it works to launch your app through your own custom URI scheme, probably even with parameters that are written to the tag. More details in my article: How to Launch Apps via Proximity APIs (NFC).

Nfc Interactor also supports peer-to-peer communication for sending messages to another device (using the standardized SNEP protocol). As you can define any kind of NDEF message in the editor, you can test how the other phone will react to incoming messages; or – in case your app is listening to incoming proximity messages – you can test how your app will react; both to planned messages, as well as if your app stays stable if it receives unexpected messages via NFC.

Open Source Nfc Code for Developers

In some scenarios, you will need to have more control over the actual NFC message contents than the Windows Proximity APIs will provide to you. Reading, understanding and implementing the complex NDEF message specifications of the NFC Forum will cost you many hours or even days of precious work time.

To make your life easier and get your new NFC apps quicker to the market, I’ve released the heart of Nfc Interactor as an open source component: the NDEF Library for Proximity APIs.

The library is collection of C# classes that works both for Windows 8 as well as for Windows Phone 8 apps. You can use it to create NDEF messages containing one or more NDEF records, as well as for reading and parsing messages you got from peers or a tag.

Using the library will for example enable you to write a cross-platform LaunchApp tag, which contains multiple records: a Windows LaunchApp record for Windows (Phone) 8, a cutom record type (external RTD) for Symbian, plus an Android Application Record for Google Android. I’ve published more details about how to get this to work at the Microsoft TechNet Wiki.

Getting Started

With NFC now being an important part of both Windows Phone 8 as well as Windows 8, you can write exciting new apps, as well as integrate NFC into your existing apps to expand your customer base or to add unique new features.

The article How to Acquire and Publish Content from / to NFC Tags and Proximity Peers contains a short and concise overview of the Proximity APIs and how to put them into use.