问题:Android 6.0的手机无法通过低版本的Mac地址获取方式获取Mac地址
WifiInfo.getMacAddress() 或者 BluetoothAdapter.getAddress()
原因:由于安全方面的原因,Google在Android 6.0以后的SDK中将上述两个方法的返回值修改为了固定的“02:00:00:00:00:00”
但是可以从NetworkInterface.getNetworkInterfaces()获取(基于调用:cat /sys/class/net/wlan0/address)
解决方案:
public static String getMac() {
try {
Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
while (interfaces.hasMoreElements()) {
NetworkInterface iF = interfaces.nextElement();
byte[] addr = iF.getHardwareAddress();
if (addr == null || addr.length == 0) {
continue;
}
StringBuilder buf = new StringBuilder();
for (byte b : addr) {
buf.append(String.format("%02X:", b));
}
if (buf.length() > 0) {
buf.deleteCharAt(buf.length() - 1);
}
String mac = buf.toString();
Log.d("mac", "interfaceName=" + iF.getName() + ", mac=" + mac);
if (iF.getName().equals("wlan0")) {
return mac;
} else {
return Build.UNKNOWN;
}
}
} catch (SocketException e) {
return Build.UNKNOWN;
}
return Build.UNKNOWN;
}
感恩!