Apps that make use of the Data Sense API require the ID_CAP_NETWORKING capability. Enable the capability by opening the WMAppManifest.xml file in design view and selecting the capability in the Capabilities tab.
The Data Sense API provides your app with the following three important pieces of information:
Whether the phone is roaming
If the user is approaching the limit of his or her data plan
If the user has exceeded the limit of his or her data plan
If the phone is roaming or the user has exceeded the data plan limit, the cost of transferring data may be high. Your app should, therefore, either not transfer data or seek permission from the user to transfer data.
If the user is approaching the limit of the data plan, your app should minimize its data usage.
The source code for this section is located in the DataDrivenApps/DataSense directory of the WPUnleashed.Examples project in the downloadable sample code. The Data Sense API is located in the Windows.Networking.Connectivity namespace.
Listing 27.11 demonstrates how to retrieve a ConnectionCost
object using the static GetInternetConnectionProfile
method of NetworkInformation
class. ConnectionCost
includes the following four properties:
ApproachingDataLimit
(of type bool
)
Roaming
(of type bool
)
OverDataLimit
(of type bool
)
NetworkCostType
(of type NetworkCostType
)
void UpdateNetworkInformation()
{
ConnectionProfile connectionProfile
= NetworkInformation.GetInternetConnectionProfile();
ConnectionCost = connectionProfile.GetConnectionCost();
if (connectionProfile.NetworkAdapter.IanaInterfaceType
== (int)IanaInterfaceTypes.Wifi
|| connectionCost.NetworkCostType == NetworkCostType.Unrestricted)
{
/* Connection is a Wi-Fi connection.
* Restricting data usage is not necessary. */
DoNotTransferData = false;
MinimizeUsage = false;
}
else
{
/* Data usage should be moderated. */
if (connectionCost.Roaming || connectionCost.OverDataLimit)
{
DoNotTransferData = true;
}
if (connectionCost.ApproachingDataLimit)
{
MinimizeUsage = true;
}
}
}
The ConnectionCost
object’s NetworkCostType
property can be one of the following values:
Unrestricted
Fixed
Variable
If the value is Unrestricted
, there is no need to limit data usage. If not Unrestricted
, your app should take into account the other three properties of the ConnectionCost
object.
If the user has not specified a data limit in the phone settings and the NetworkCostType
is equal to Unknown, it is up to you to choose the best behavior for your app. When Unknown, the value of ApproachingDataLimit and OverDataLimit is false. The Roaming property returns an accurate value even when the NetworkCostType is Unknown.
Note
Unfortunately, you cannot use the Simulation Dashboard to test your Data Sense code by switching the network type from Wi-Fi to a cellular option. The Simulation Dashboard does not change the values of the properties that the Data Sense API uses.
18.117.11.247