一开始是android6.0的问题,可以用下面的'MacUtils'类解决,但是当用华为mate 9时(android7.0),结果返回值又是空,只好另想办法。(android8.0下面方法已无效,暂时没想到解决办法)
public class MacUtils {
/**
* 获取手机的MAC地址
*
* @return
*/
public static String getMac() {
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();
}
if ("".equals(macSerial)) {
try {
return loadFileAsString("/sys/class/net/eth0/address")
.toUpperCase().substring(0, 17);
} catch (Exception e) {
e.printStackTrace();
}
}
return macSerial;
}
private static String loadFileAsString(String fileName) throws Exception {
FileReader reader = new FileReader(fileName);
String text = loadReaderAsString(reader);
reader.close();
return text;
}
private static String loadReaderAsString(Reader reader) throws Exception {
StringBuilder builder = new StringBuilder();
char[] buffer = new char[4096];
int readLength = reader.read(buffer);
while (readLength >= 0) {
builder.append(buffer, 0, readLength);
readLength = reader.read(buffer);
}
return builder.toString();
}
}
解决华为mate 9(不知道其他手机是否一样)
/**
* 获取蓝牙地址
*/
public static String getMac(Context context) {
return android.provider.Settings.Secure.getString(context.getContentResolver(), "bluetooth_address");
}
网友评论