Determine your Android device’s internet connection status

An internet connection can do wonders to virtually any mobile application in terms of functionality, content, personalization, and many more. You can easily set up a user registration system to create a personalized UX, allow users to sync app data across their devices, or even allow users to interact with each other.
The list of possibilities is pretty much endless, and in this day in age, it’s perfectly reasonable to assume that if someone owns a mobile device – that device is probably somehow connected to the internet.

As a result, obviously many mobile applications today rely on an internet connection in order to function. But what if the internet connection is lost? Should the app crash because the user entered an elevator or a concrete tunnel? Of course not. We would like to provide some limited functionality if possible, and perhaps notify the users about the issue, so they will at least know why the app suddenly stopped behaving as expected.
Today I’m going to show you how to take these matters into your own hands – Make your app aware of any change in the device’s connectivity state, and even get some useful information like the network name (if exists) and gateway IP (useful if you’re implementing a Zeroconf service in your app, for example).

Before We Begin

This tutorial assumes you are familiar with Java and the Android platform (don’t worry, basic knowledge will suffice). If you are completely new to either of these things, then you might get a little lost in this tutorial.

Prerequisites & Permissions

Before we begin you will need to have an Android app project that you are currently developing. The app will, of course, need access to the internet and the state of the wifi and cellular network components.
If you haven’t already done this, you will need to give your app permission to access the internet. You can do this by adding these lines of code to the app’s manifest XML file:

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

You can add this line above the application tag.
If you would also like the ability to turn the wifi connection on and off, you will also need this line:

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

Detecting Internet Connectivity State Changes

For this part we will implement a Broadcast Receiver, which is basically a way for your app to listen and respond to application or system events. You can even use this class to listen to events across different apps. In our case, we will listen to changes in the device’s internet connectivity state:

BroadcastReceiver networkChangeReceiver = new BroadcastReceiver() {
		@Override
		public void onReceive(Context context, Intent intent) {
			// do stuff...
		}
	};

Now, using an Intent Filter, register the receiver to listen to the “connectivity change” notification. It’s also very recommended to unregister the receiver once you don’t need it:

registerReceiver(networkChangeReceiver, new IntentFilter("android.net.conn.CONNECTIVITY_CHANGE"); // register the receiver
unregisterReceiver(networkChangeReceiver); // unregister the receiver

Now your app will listen for changes in the device’s internet connectivity state, and call the “onReceive” method every time a change happens.

Getting Network Info

Internet Connectivity Type

Okay, your app can now detect internet connectivity changes. Now we would like to get some information about the connectivity state. We will use a Connectivity Manager to determine the connection type:

ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);		
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
if (activeNetwork != null) { // connected to the internet
	if (activeNetwork.getType() == ConnectivityManager.TYPE_WIFI) {
		// connected to wifi
	} else if (activeNetwork.getType() == ConnectivityManager.TYPE_MOBILE) {
		// connected to the mobile provider's data plan
	}
} else {
// not connected to the internet
}

Wifi Network Name

Say the device is connected to a Wifi network, and you would like to retrieve the name of the network. We will use a Telephony Manager for this:

WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
String wifiName = wifiManager.getConnectionInfo().getSSID();
if (wifiName != null && !wifiName.contains("unknown ssid")){
	// wifiName is the network name
} else {
	// network name unknown
}

Mobile Network Name

If the device is connected to the internet via a mobile network, you can retrieve the name of the network. With a Wifi Manager like this:

TelephonyManager tm = (TelephonyManager)context.getSystemService(Context.TELEPHONY_SERVICE);
String networkName tm.getNetworkOperatorName();
if (networkName != null){
	// networkName is the network name
} else {
	// network name unknown
}

Gateway IP Address

For this part, we would need to implement a method to translate the WifiManager’s gateway field (int) to a human-readable String in IP format. The method should look something like this:

public String intToIp(int i) {
return ((i >> 24 ) & 0xFF ) + "." +
	((i >> 16 ) & 0xFF) + "." +
	((i >> 8 ) & 0xFF) + "." +
	( i & 0xFF) ;
}

Now we can use the method with the WifiManager to get the gateway IP:

WifiManager wm = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
String gateway = intToIp(wm.getDhcpInfo().gateway);

Switch Wifi On/Off

Switching the device’s Wifi component on or off is easy as one line of code using the WifiManager:

wm.setWifiEnabled(true); // or false

You can even load the Wifi networks part of the device settings, also with one line of code:

startActivity(new Intent(Settings.ACTION_WIFI_SETTINGS));

That’s it! Now we have all the tools we need to detect changes in the device’s internet connectivity, and respond accordingly. Now you can design your app and UI to provide limited functionality when not connected at all, or even postpone network-related tests to reduce bandwidth use if the device is connected to a mobile data plan. It’s all up to you and the sky’s the limit.

In the holiday spirit, I have decided to also provide you some example code. I have put together a utility class and an example project showcasing everything that is discussed in this post. You can find everything in the Panda-OS GitHub repository. Feel free to clone, fork, and even contribute and make it better!

Hope you’ve enjoyed this post. I’d love to hear your questions, comments, and ideas if you have any.

Happy Holidays! 🙂

One thought on “Determine your Android device’s internet connection status

Leave a Reply

Your email address will not be published. Required fields are marked *