Skip to content

Instantly share code, notes, and snippets.

@unclechen
Created October 12, 2016 10:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save unclechen/c9f2b964845e2c843b527391b9dedd31 to your computer and use it in GitHub Desktop.
Save unclechen/c9f2b964845e2c843b527391b9dedd31 to your computer and use it in GitHub Desktop.
Android上读取MAC地址的方法,兼容Android M
// hacking mac
public static String getMacAddress(Context context) {
String macAddress = null;
try {
String wifiInterfaceName = "wlan0";
Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
while (interfaces.hasMoreElements()) {
NetworkInterface iF = interfaces.nextElement();
if (iF.getName().equalsIgnoreCase(wifiInterfaceName)) {
byte[] addr = iF.getHardwareAddress();
if (addr == null || addr.length == 0) {
return null;
}
StringBuilder buf = new StringBuilder();
for (byte b : addr) {
buf.append(String.format("%02X:", b));
}
if (buf.length() > 0) {
buf.deleteCharAt(buf.length() - 1);
}
macAddress = buf.toString();
break;
}
}
} catch (SocketException se) {
macAddress = null;
}
if (TextUtils.isEmpty(macAddress)) {
android.net.wifi.WifiManager wifi = (android.net.wifi.WifiManager) context.getSystemService(Context.WIFI_SERVICE);
macAddress = wifi.getConnectionInfo().getMacAddress();
}
return macAddress;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment