Programmatically Getting the MAC of an Android Device

How to find MAC address of an Android device programmatically

WifiManager wifiManager = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);
WifiInfo wInfo = wifiManager.getConnectionInfo();
String macAddress = wInfo.getMacAddress();

Also, add below permission in your manifest file

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

Please refer to Android 6.0 Changes.

To provide users with greater data protection, starting in this release, Android removes programmatic access to the device’s local hardware identifier for apps using the Wi-Fi and Bluetooth APIs. The WifiInfo.getMacAddress() and the BluetoothAdapter.getAddress() methods now return a constant value of 02:00:00:00:00:00.

To access the hardware identifiers of nearby external devices via Bluetooth and Wi-Fi scans, your app must now have the ACCESS_FINE_LOCATION or ACCESS_COARSE_LOCATION permissions.

Can one programmatically obtain the MAC address of a device running Android 6.0+?

You can use an alternative way to get the MAC addr on a Android 6.0 device.

First add Internet User-Permission to your AndroidManifest.xml:

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

Secondly,

try {
// get all the interfaces
List<NetworkInterface> all = Collections.list(NetworkInterface.getNetworkInterfaces());
//find network interface wlan0
for (NetworkInterface networkInterface : all) {
if (!networkInterface.getName().equalsIgnoreCase("wlan0")) continue;
//get the hardware address (MAC) of the interface
byte[] macBytes = networkInterface.getHardwareAddress();
if (macBytes == null) {
return "";
}

StringBuilder res1 = new StringBuilder();
for (byte b : macBytes) {
//gets the last byte of b
res1.append(Integer.toHexString(b & 0xFF) + ":");
}

if (res1.length() > 0) {
res1.deleteCharAt(res1.length() - 1);
}
return res1.toString();
}
} catch (Exception ex) {
ex.printStackTrace();
}


Related Topics



Leave a reply



Submit