Detect Network Connection

PDF for offline use
Sample Code:
Related SDKs:

Let us know how you feel about this

Translation Quality


last updated: 2017-01

This recipe provides some quick snippets on how detect the type of network connection in use or how to query a specific type of network connection.


The Android.Net.ConnectivityManager class provides information about all the possible network connections for an Android device. In order to query the network state, the application must request a NetworkInfo object for a type of network. The NetworkInfo class which holds information about a given network type. A instance of NetworkInfo is obtained by calling the GetNetworkInfo member of the ConnectivityManager class. This method takes a ConnectivityType describing which network to query for more information.

This image shows the sample application for this recipe running while connected to different networks:


This recipe requires Android 5.0 (API level 21) or higher.

Using ConnectivityManager

The first thing the sample application must do is obtain a reference to the ConnectivityManager:

ConnectivityManager connectivityManager = (ConnectivityManager) GetSystemService(ConnectivityService);

In order to query the device for network state, the app must request the android.permission.ACCESS_NdETWORK_STATE in the manifest:

<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"></uses-permission>

Connected to a Network

To check if the device is connected to any type of network the ActiveNetworkInfo property of ConnectivityManager returns information about the type of network the device is using. The app uses this NetworkInfo object to see if the device is connected:

NetworkInfo networkInfo = connectivityManager.ActiveNetworkInfo;
bool isOnline = networkInfo.IsConnected;

Connected to WiFi

The property NetworkInfo.Type returns a ConnectivityType value which can be checked to see if the device is connected to a WiFi network:

bool isWifi = networkInfo.Type == ConnectivityType.Wifi;
    Log.Debug(TAG, "Wifi connected.");
} else
    Log.Debug(TAG, "Wifi disconnected.");

Detect When Roaming

The .IsRoaming property on the NetworkInfo class is a boolean value that is used to determine if they device is roaming while connected to a mobile network. The following code snippet from the sample application will display a green square when the device is roaming, and a red square when it is not:

if (networkInfo.IsRoaming)
    Log.Debug(TAG, "Roaming.");
} else
    Log.Debug(TAG, "Not roaming.");

Xamarin Workbook

If it's not already installed, install the Xamarin Workbooks app first. The workbook file should download automatically, but if it doesn't, just click to start the workbook download manually.