Saturday, October 2, 2021

Code to get WiFi MAC Address of Device in Android

 In Android we can get the MAC Address of a Device

Code to get WiFi MAC Address of Device in Android

if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
// only for gingerbread and newer versions
macAddressOfDevice = getMacAddr();
Log.i("KAMLESH", "MAC Address : " + macAddressOfDevice);
}
else {
WifiManager wifiMan = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);
WifiInfo wifiInf = wifiMan.getConnectionInfo();
macAddressOfDevice = wifiInf.getMacAddress();
Log.i("KAMLESH", "MAC Address : " + macAddressOfDevice);
}


public  String getMacAddr() {
try {
List<NetworkInterface> all = Collections.list(NetworkInterface.getNetworkInterfaces());
for (NetworkInterface nif : all) {
if (!nif.getName().equalsIgnoreCase("wlan0")) continue;

byte[] macBytes = nif.getHardwareAddress();
if (macBytes == null) {
return "";
}

StringBuilder res1 = new StringBuilder();
for (byte b : macBytes) {
res1.append(String.format("%02X:",b));
}

if (res1.length() > 0) {
res1.deleteCharAt(res1.length() - 1);
}
return res1.toString();
}
} catch (Exception ex) {
}
return "02:00:00:00:00:00";
}

Check Internet Connection Type In Android

 In Android we can check whether the Device is Connected to Internet or Not.


If Connected to Internet, we can check the type of connection like Mobile Data, WiFi etc


Add following permission in Manifest file

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

Code to Check Internet Connection Type in Android


public boolean isInternetConnected() {
ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);

NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
boolean isConncted = activeNetworkInfo != null && activeNetworkInfo.isConnectedOrConnecting();
return isConncted;
}


public boolean isConnectedWifi(){
ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo info = connectivityManager.getActiveNetworkInfo();
return (info != null && info.isConnected() && info.getType() == ConnectivityManager.TYPE_WIFI);
}



public boolean isConnectedMobile(){
ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo info = connectivityManager.getActiveNetworkInfo();
return (info != null && info.isConnected() && info.getType() == ConnectivityManager.TYPE_MOBILE);
}