Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

31 Days of Mango | Day #10: Network Info

DZone's Guide to

31 Days of Mango | Day #10: Network Info

· Mobile Zone
Free Resource

Launching an app doesn’t need to be daunting. Whether you’re just getting started or need a refresher on mobile app testing best practices, this guide is your resource! Brought to you in partnership with Perfecto

This article is Day #10 in a series called 31 Days of Mango.

Day10-NetworkInformation

Today we are going to look at the NetworkInformation namespace in the Windows Phone 7.1 SDK.  This set of APIs gives us insight into abundant amount of data on a user’s device, as it relates to their network connection availability, type, and more.

What is the NetworkInformation namespace?

Ultimately, it’s a collection of classes for Windows Phone that give you a ton of information about the network connectivity of a specific device.  There are two sections of this namespace that we are going to focus on in this article:

  • DeviceNetworkInformation – a set of properties that allow us to check what connectivity is enabled on the user’s device.
  • NetworkInterfaceList – an actual list of all of the networks that a user’s device is connected to. This includes their carrier as well as wireless networks.

While there are the obvious reasons to know about a user’s connectivity, I’ve heard some pretty interesting ways to use this information in your app.  For example, think about an application that administers some sort of academic test.  You don’t want the user to be able to use the internet to answer the questions, so you can detect that the phone doesn’t have any network connections.  Or perhaps you’ve got an app that lets users download new e-books.  Knowing whether the user has a connection might let you prompt the user that they need to connect to the internet before they can browse your catalog.

Using DeviceNetworkInformation

DeviceNetworkInformation is a set of five boolean and string values that we can use to determine what types of network connectivity the user currently has available.  A list and description of each of these values is below:

CellularMobileOperator Gives you the name of the cellular provider the device is currently connected to. string
IsNetworkAvailable The most common value you will use, this only determines whether the device has network connectivity.  This does not determine internet access, only that the phone is connected to a network. boolean
IsCellularDataEnabled Shows you whether or not the user’s device has cellular data available. boolean
IsCellularDataRoamingEnabled Shows you whether or not the user is allowing cellular data roaming.  This is generally set to false by default. boolean
IsWifiEnabled Determines whether or not the device has wifi enabled. boolean
NetworkAvailabilityChanged This is an event handler that we can use to recognize a change in the device’s network connectivity.

 

To get started building our application, I’ve kept the user interface incredibly simple this time.  We’re only adding a TextBlock, inside of a ScrollViewer control.  If you’ve been building the apps along with the previous articles, you know the drill.  The following code is your XAML interface for your MainPage.xaml file.

<phone:PhoneApplicationPage
   x:Class="Day10_NetworkInformation.MainPage"
   xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
   xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
   xmlns:phone="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone"
   xmlns:shell="clr-namespace:Microsoft.Phone.Shell;assembly=Microsoft.Phone"
   xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
   xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
   mc:Ignorable="d" d:DesignWidth="480" d:DesignHeight="768"
   FontFamily="{StaticResource PhoneFontFamilyNormal}"
   FontSize="{StaticResource PhoneFontSizeNormal}"
   Foreground="{StaticResource PhoneForegroundBrush}"
   SupportedOrientations="Portrait" Orientation="Portrait"
   shell:SystemTray.IsVisible="True">

    <Grid x:Name="LayoutRoot" Background="Transparent">
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="*"/>
        </Grid.RowDefinitions>

        <StackPanel x:Name="TitlePanel" Grid.Row="0" Margin="12,17,0,28">
            <TextBlock x:Name="ApplicationTitle" Text="31 DAYS OF MANGO - DAY #10" Style="{StaticResource PhoneTextNormalStyle}"/>
            <TextBlock x:Name="PageTitle" Text="network information" Margin="9,-7,0,0" Style="{StaticResource PhoneTextTitle1Style}"/>
        </StackPanel>

        <Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
            <ScrollViewer>
                <TextBlock x:Name="ContentBox" FontSize="20" />
            </ScrollViewer>
        </Grid>
    </Grid>
</phone:PhoneApplicationPage> 

We will be writing all of our values to that TextBlock in this application, so we won’t be revisiting the UI.  Pretty boring, actually, but it lets us focus on the purpose of this article, which is using C# to determine the network capabilities of our user’s device.

In the example below, you will see that I register the NetworkAvailabilityChanged event handler in the MainPage() method, and then grab all of the values from the DeviceNetworkInformation class.  You can use this code in your MainPage.xaml.cs file.

using System;
using System.Text;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Net.NetworkInformation;

namespace Day10_NetworkInformation
{
    public partial class MainPage : PhoneApplicationPage
    {

        public MainPage()
        {
            InitializeComponent();
            DeviceNetworkInformation.NetworkAvailabilityChanged += new EventHandler<NetworkNotificationEventArgs>(DeviceNetworkInformation_NetworkAvailabilityChanged);
            GetData();
        }

        private void GetData()
        {
            StringBuilder info = new StringBuilder();
            
            if (DeviceNetworkInformation.CellularMobileOperator != null)
                info.AppendLine("carrier: " + DeviceNetworkInformation.CellularMobileOperator.ToLower());

            info.AppendLine("network: " + DeviceNetworkInformation.IsNetworkAvailable.ToString());
            info.AppendLine("roaming: " + DeviceNetworkInformation.IsCellularDataRoamingEnabled.ToString());
            info.AppendLine("cellular: " + DeviceNetworkInformation.IsCellularDataEnabled.ToString());
            info.AppendLine("wifi: " + DeviceNetworkInformation.IsWiFiEnabled.ToString());

            ContentBox.Text = info.ToString();
        }

        void DeviceNetworkInformation_NetworkAvailabilityChanged(object sender, NetworkNotificationEventArgs e)
        {
            GetData();
        }
    }
}
 

If you’ve been coding along with this article, you can run your project at this point.  You will see a screen that looks like the image below if you use the Windows Phone emulator.

image

In the next section, we are going to look at the NetworkInterfaceList, which contains information about every one of the networks that the device is currently connected to.

Using the NetworkInterfaceList

The NetworkInterfaceList contains a list of each of the individual networks that the user’s device is connected to.  This includes wireless networks, cellular networks, and even the ethernet connection that Windows Phones use when plugged into a PC.

In our example, we are going to loop through the entire collection of networks, but because NetworkInterfaceList is an IEnumerable, you can parse through it just about any way you’d like using LINQ.  In the code below, you’ll see that I just loop through the entire list, writing each of them to the screen that the user can see everything they are currently connected to.  I have only included the GetData() method from the earlier example, so make sure to replace it in the code you’re writing.

private void GetData()
{
    StringBuilder info = new StringBuilder();

    if (DeviceNetworkInformation.CellularMobileOperator != null)
        info.AppendLine("carrier: " + DeviceNetworkInformation.CellularMobileOperator.ToLower());

    info.AppendLine("network: " + DeviceNetworkInformation.IsNetworkAvailable.ToString());
    info.AppendLine("roaming: " + DeviceNetworkInformation.IsCellularDataRoamingEnabled.ToString());
    info.AppendLine("cellular: " + DeviceNetworkInformation.IsCellularDataEnabled.ToString());
    info.AppendLine("wifi: " + DeviceNetworkInformation.IsWiFiEnabled.ToString());

    info.AppendLine();

    foreach (var n in new NetworkInterfaceList())
    {
        info.AppendLine(n.InterfaceName.ToLower());
        info.AppendLine(n.InterfaceType.ToString());
        info.AppendLine(n.InterfaceState.ToString());
        info.AppendLine();
    }

    ContentBox.Text = info.ToString();
}
 

Using the emulator, you’ll get the following networks listed in your application:

image

On an actual device, you’ll likely get around 4 networks in your list.  For example, on mine I have a wireless connection, my carrier’s internet connection, my carrier’s mms connection, and the software loopback interface (which you can read more about here).

Summary

Today, I showed the NetworkInformation namespace, and how we can use it in our applications to determine whether a user’s device is connected to a network, or in some cases, not connected.

If you would like to download the full sample application that was built in this article, you can download it from the Download Code button below.

download

Tomorrow, we are going to take a deep look at Live Tiles, and how we can create and edit them from our applications now.  See you then!

toolsbutton5



Source: http://www.jeffblankenburg.com/2011/11/10/31-days-of-mango-day-10-network-information/

Keep up with the latest DevTest Jargon with the latest Mobile DevTest Dictionary. Brought to you in partnership with Perfecto.

Topics:

Opinions expressed by DZone contributors are their own.

THE DZONE NEWSLETTER

Dev Resources & Solutions Straight to Your Inbox

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

X

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}