Recipe 9.3 Checking Network State
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); ...Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access