Recipe 9.3 Checking Network State

Android Versions
Level 1 and above
Permissions
ACCESS_NETWORK_STATE
CHANGE_WIFI_STATE
Source Code to Download from Wrox.com
CheckNetworkState.zip

If you are writing a network application, it is important that you check whether the device is currently connected to a network, such as a Wi-Fi network, or the data network (3G or 4G). This recipe shows how to do this using the ConnectivityManager class.

Solution

To check for network connectivity, use the ConnectivityManager class. In the following code snippet, you first obtain an instance of the ConnectivityManager class and then use the getNetworkInfo() method to get information about the Wi-Fi (ConnectivityManager.TYPE_WIFI) and data network (ConnectivityManager.TYPE_MOBILE). The getNetworkInfo() method returns an instance of the NetworkInfo class. Using this instance, you can determine whether a network type is connected or not:

package com.example.checknetworkstate;

import android.app.Activity;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.view.Menu;
import android.widget.Toast;

public class MainActivity extends Activity {
    ConnectivityManager connectivity;
    NetworkInfo wifiNetworkInfo, mobileNetworkInfo; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main);  ...

Get Android Application Development Cookbook: 93 Recipes for Building Winning Apps now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.