安卓8.1更新了获取WIFI地址的方法,使用之前的方法获取不到地址
private String getWifiMacAddress() {
String str = "";
String macSerial = "";
try {
Process pp = Runtime.getRuntime().exec(
"cat /sys/class/net/wlan0/address ");
InputStreamReader ir = new InputStreamReader(
pp.getInputStream());
LineNumberReader input = new LineNumberReader(ir);
for (; null != str; ) {
str = input.readLine();
if (str != null) {
macSerial = str.trim();// 去空格
break;
}
}
} catch (Exception ex) {
ex.printStackTrace();
}
return macSerial;
}
更新使用以下方法即可获取到wifi地址,我自己遇到的Android 8.1机型测试可以获取,可能不同的机型不一定能获取到,或者需要用其他方法了,下面的方法仅作参考,之前有误 请修改成wlan0,这段代码执行之前需要先打开wifi才能获取到
private String getWifiMacAddress() {
String defaultMac = "02:00:00:00:00:00";
try {
List<NetworkInterface> interfaces = Collections
.list(NetworkInterface.getNetworkInterfaces());
for (NetworkInterface ntwInterface : interfaces) {
if (ntwInterface.getName().equalsIgnoreCase("wlan0")) {//之前是p2p0,修正为wlan
byte[] byteMac = ntwInterface.getHardwareAddress();
if (byteMac == null) {
// return null;
}
StringBuilder strBuilder = new StringBuilder();
for (int i = 0; i < byteMac.length; i++) {
strBuilder.append(String
.format("%02X:", byteMac[i]));
}
if (strBuilder.length() > 0) {
strBuilder.deleteCharAt(strBuilder.length() - 1);
}
return strBuilder.toString();
}
}
} catch (Exception e) {
// Log.d(TAG, e.getMessage());
}
return defaultMac;
}