今天找了一下午的资料,总算是OK了
感谢这个同学的分享http://blog.csdn.net/zxw136511485/article/details/52161269
之前咱用的API在6.0系统上运行,获取的结果是: 02:00:00:00:00:00
public WifiAdmin(Context context) {
mContext = context;
mWifiManager = (WifiManager) context
.getSystemService(Context.WIFI_SERVICE);
mWifiInfo = mWifiManager.getConnectionInfo();
}
public String getMac(){
return mWifiInfo.getMacAddress();
}
解决办法如下:已测试过,能正常获取,大家可以直接试用
public class MacUtil {
/**
* 获取手机的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 (macSerial == null || "".equals(macSerial)) {
try {
return loadFileAsString("/sys/class/net/sit0/address")
.toUpperCase().substring(0, 17);
} catch (Exception e) {
e.printStackTrace();
}
}
return macSerial;
}
public static String loadFileAsString(String fileName) throws Exception {
FileReader reader = new FileReader(fileName);
String text = loadReaderAsString(reader);
reader.close();
return text;
}
public 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();
}
}
注意: 1,我们去找Mac address时,需要查看自己手机系统里的真实路径是什么,比如我测试的ZUK手机获取wlan mac的路径是/sys/class/net/sit0/address
2,需要添加相应的权限
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
3,获取mac,前提wlan一定要已经打开