Random geekery since 2005.

Husband, father, programmer, speaker, writer, blogger, podcaster, collector, traveler, golfer.

31 Days of Mango | Day #10: Network Information

Written in

by

Day10-NetworkInformationDay9-CalendarAPIDay8-ContactsAPIDay7-RawCameraDay6-Motion

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

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.

If you would like to download the sample application from this article to your Windows Phone, it is available in the Windows Phone Marketplace.

DownloadIcon

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&quot;
   xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml&quot;
   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&quot;
   xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006&quot;
   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

Tags

11 responses to “31 Days of Mango | Day #10: Network Information”

  1. […] Der Originalartikel befindet sich hier: Day #10: Network Information. […]

  2. […] Posts:What I Learned In WP7 – Issue 1631 Days of Mango | Day #10: Network Information31 Days of Mango | Day #5: Gyroscope31 Days of Mango | Day #4: Compass31 Days of Mango | Day #9: […]

  3. […] 31 Days of Mango | Day #10: Network Information – Jeff Blankenburg continues his 31 days of Mango series with a look at the NetworkInformation namespace which reveal information abou the network connectivity available and its state on the device. […]

  4. […] 31 Days of Mango | Day #10: Network Information […]

  5. […] 31 Days of Mango | Day #10: Network Information […]

  6. […] Este artículo es una traducción de Day 1: Network Information, puedes encontrarlo aquí en la vers… […]

  7. […] Англоязычная версия статьи доступна здесь. […]

  8. Ram Patil Avatar
    Ram Patil

    I use a button under Wi-Fi status to enable/disable it. On button click I start the ConnectionSettingsTask to change the status. And if I come back to app screen I don’t see status updated. Moreover I did not see NetworkAvailabilityChanged event firing. What could be the reason?

    1. Martin Stolz Avatar

      Did you disconnet your device from the PC? Otherwise the phone is still using the ethernet connection of your PC!
      So disconnect your device before testing networking issues.

  9. Eduard Avatar
    Eduard

    Any way to get signal strength? Working on a triangulation project and require signal strength between gateways to determine position. Many thanks

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

Create a website or blog at WordPress.com

%d bloggers like this: