Check Network connectivity and obtain Wifi MAC address in Android

less than 1 minute read

Updated: 2012-05-09

Today I wanted to check if my Android device is connected to a TCP/IP network. So I searched in the web for a while and I found this StackOverFlow answer on connectivity.

public boolean isOnline() {
	ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
	NetworkInfo netInfo = cm.getActiveNetworkInfo();
	if (netInfo != null && netInfo.isConnectedOrConnecting()) {
		return true;
	}
	return false;
}

Also I wanted to obtain my Wifi network card MAC address. The code snippet to do this is the following:

/**
 * Get Wifi network card MAC address 
 * @return mac address String
 */
public String getMacAddress() {
	WifiManager wifiMan = (WifiManager) this.getSystemService(Context.WIFI_SERVICE);
	WifiInfo wifiInf = wifiMan.getConnectionInfo();
	
	return wifiInf.getMacAddress();	
}

The above methods require javaandroid.permission.ACCESS_NETWORK_STATE android.permission.ACCESS_WIFI_STATE uses permissions in AndroidManifest.xml file.

Comments