MobileUtilizing DataSense to Build Data-Cap Sensitive Applications in Windows Phone 8

Utilizing DataSense to Build Data-Cap Sensitive Applications in Windows Phone 8

Developer.com content and product recommendations are editorially independent. We may make money when you click on links to our partners. Learn More.

Introduction

Microsoft introduced Data Sense as part of Windows Phone 8, which allows apps to restrict their data consumption over the cellular data plans. This feature is immensely useful if the user is on a capped plan and the application you are building gobbles up bandwidth like a desert camel drinking water.

Data Sense Basics

Data Sense monitors a phone’s data usage and punts some tasks until the user has a Wi-Fi connection.

Data Sense is a feature that is activated by the mobile carrier, so it might not be present on all phones.  Users have to contact their mobile carrier to see if this feature is available and if so, have it activated.

How it Works

If the feature is available, users can open the Data Sense application and tap Settings-> Set Limit to specify the limits that need to be monitored. Three types of limits can be selected:

  • One time – To specify a limited amount of data usage by a certain date.
  • Monthly – To specify a limited amount of data usage on a monthly basis.
  • Unlimited – To not specify a cap of data usage. This option can be useful to track down which apps use the most bandwidth.

Data Sense can also restrict background data, which is used by a lot of applications to update at regular intervals (without user input). Users can specify a restriction on background data by tapping Settings -> “Restrict background data when I’m near my limit” checkbox.

Please note that Data Sense is not available with all providers. In the US, Verizon offers this.

Hands-On

To build a Windows Phone application that can respect and work with data caps set by Data Sense limits, Microsoft has provided APIs that allows Windows Phone programmers to check a user’s data usage.

Let us walk through a scenario of building a Windows Phone application that respects Data Sense settings.

Create a new Visual Studio 2012 project titled WindowsPhoneDataSenseDemo.

Create a new Visual Studio 2012 project
Create a new Visual Studio 2012 project

When prompted, select Windows Phone OS 8.0 as the target platform.

Target Windows Phone OS Version
Target Windows Phone OS Version

Next, we need to declare the capability to allow use of Data Sense APIs. This capability is declared as ID_CAP_NETWORKING in the WMAppManifest.xml file.

WMAppManifest.xml
WMAppManifest.xml

Double click WMAppManifest.xml file in the Solution Explorer and ensure ID_CAP_NETWORKING is selected.

WMAppManifest.xml Capabilities
WMAppManifest.xml Capabilities

Now, add a few controls as shown in the diagram.

Add Controls
Add Controls

There is one checkbox that indicates whether using Data is allowed or not, and another checkbox that indicates whether high resolution is allowed or not. Additionally, we add a textBlock and a textbox to show the data cost.

Next, in the code-behind for MainPage.xaml (MainPage.xaml.cs), include the following namespace

using Windows.Networking.Connectivity;

Next, add an instance of NetworkStatusChangedEventHandler variable to the MainPage class.

namespace WindowsPhoneDataSenseDemo
{
    public partial class MainPage : PhoneApplicationPage
    {
        NetworkStatusChangedEventHandler networkStatusEventCallback;
        // Constructor
        public MainPage()

Next, we implement a method, which gets the network connection profile and network connection cost information to populate the controls that we created above.

The network adapter for Wi-fi has the enumeration value of 71, so we will check that for our logic.

private void UpdateNetworkInformation()
        {
            
            ConnectionProfile myConnectionProfile = Windows.Networking.Connectivity.NetworkInformation.GetInternetConnectionProfile();
            ConnectionCost myConnectionCost = myConnectionProfile.GetConnectionCost();
            // Check the connection details for An IEEE 802.11 wireless network interface. See http://msdn.microsoft.com/en-us/library/windows/apps/windows.networking.connectivity.networkadapter.ianainterfacetype.aspx for details
            if (myConnectionProfile.NetworkAdapter.IanaInterfaceType != 71)
            {
                
                
                if (myConnectionCost.Roaming)
                {
                    
                    checkBoxSendData.IsChecked = false;
                }
 
                if (myConnectionCost.ApproachingDataLimit)
                {
                    
                    checkboxHighResAllowed.IsChecked = false;
                }
 
                if (myConnectionCost.OverDataLimit)
                {
                    
                    checkBoxSendData.IsChecked = false;
                }
            }
            else
            {
                // Connection is a Wi-Fi connection. Yay, things are unthrottled
                checkBoxSendData.IsChecked = true;
                checkboxHighResAllowed.IsChecked = true;
            }
 
            
            string networkCostValue = string.Empty;
            switch (myConnectionCost.NetworkCostType)
            {
                case NetworkCostType.Unrestricted:
                    networkCostValue += "Cost: Unrestricted";
                    break;
                case NetworkCostType.Fixed:
                    networkCostValue += "Cost: Fixed";
                    break;
                case NetworkCostType.Variable:
                    networkCostValue += "Cost: Variable";
                    break;
                case NetworkCostType.Unknown:
                    networkCostValue += "Cost: Unknown";
                    break;
                default:
                    networkCostValue += "Cost: Error";
                    break;
            }
            networkCostValue += "n";
            networkCostValue += "Roaming: " + myConnectionProfile.GetConnectionCost().Roaming + "n";
            networkCostValue += "Over Data Limit: " + myConnectionProfile.GetConnectionCost().OverDataLimit + "n";
            networkCostValue += "Approaching Data Limit : " + myConnectionProfile.GetConnectionCost().ApproachingDataLimit + "n";
 
            textBoxCosts.Text = networkCostValue;
 
        }

 

Next, we implement the delegate method, which  needs to be called when network status changes. In this method, we call the UpdateNetworkInformation() method we just implemented.

private void OnNetworkStatusChange(object sender)
        {
            UpdateNetworkInformation();
 
        }

Finally, in the constructor for MainPage.xaml, we initialize the NetworkStatusChangedEventHandler  event handler, passing in the delegate we just created.

public partial class MainPage : PhoneApplicationPage
    {
        NetworkStatusChangedEventHandler networkStatusEventCallback;
        // Constructor
        public MainPage()
        {
            InitializeComponent();
            networkStatusEventCallback = new NetworkStatusChangedEventHandler(OnNetworkStatusChange);
            UpdateNetworkInformation();
 
            // Sample code to localize the ApplicationBar
            //BuildLocalizedApplicationBar();
        }

The Data Sense logic of our application is complete.

In a functional application, before any data operation (like saving or retrieving), the application will check for checkBoxSendData.IsChecked before sending data over the network and will check for checkBoxHighResAllowed.IsChecked before sending high resolution pictures. If these settings do not allow the task to be completed, the application will need to queue the task for later.

A sample code listing of this lab is available at <link>.

Summary

In this article, we learned how to build Windows Phone applications that respect Data Sense. I hope you have found this information useful.

About the author

Vipul Patel is a Program Manager currently working at Amazon Corporation. He has formerly worked at Microsoft in the Lync team and in the .NET team (in the Base Class libraries and the Debugging and Profiling team). He can be reached at vipul.patel@hotmail.com  
 

Get the Free Newsletter!

Subscribe to Developer Insider for top news, trends & analysis

Latest Posts

Related Stories