Android 手機獲取Mac地址的方法
阿新 • • 發佈:2018-12-07
轉載地址:https://blog.csdn.net/yushuangping/article/details/83245847
這期需求,要求從系統裝置上獲取一個唯一碼作為當前登入使用者的唯一標識,最後決定採用mac地址。
第一種:
官方獲取mac地址的方法是:
-
/**
-
* 通過WiFiManager獲取mac地址
-
* @param
context
-
* @return
-
*/
-
private static String tryGetWifiMac(Context context) {
-
WifiManager wm = (WifiManager) context.getApplicationContext().getSystemService(Context.WIFI_SERVICE);
-
WifiInfo wi = wm.getConnectionInfo();
-
if (wi ==
null || wi.getMacAddress() ==
null) {
-
return
null;
-
}
-
if (
"02:00:00:00:00:00".equals(wi.getMacAddress().trim())) {
-
return
null;
-
}
else {
-
return wi.getMacAddress().trim();
-
}
-
}
這個方法Android 7.0是獲取不到的,返回的是null,其實是返回“02:00:00:00:00:00”
第二種方法:
通過shell命令的方式來獲取:
-
**
-
* 這是使用adb shell命令來獲取mac地址的方式
-
*
@return
-
*/
-
public static String getMac() {
-
String macSerial =
null;
-
String str =
"";
-
-
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 (IOException ex) {
-
// 賦予預設值
-
ex.printStackTrace();
-
}
-
return macSerial;
-
}
這種方式Android7.0以上版本也是獲取不到
第三種方法:
根據網路介面獲取:
-
/**
-
* 通過網路介面取
-
* @return
-
*/
-
private
static String getNewMac() {
-
try {
-
List<NetworkInterface> all = Collections.
list(NetworkInterface.getNetworkInterfaces());
-
for (NetworkInterface nif : all) {
-
if (!nif.getName().equalsIgnoreCase(
"wlan0"))
continue;
-
-
byte[] macBytes = nif.getHardwareAddress();
-
if (macBytes ==
null) {
-
return
null;
-
}
-
-
StringBuilder res1 =
new StringBuilder();
-
for (byte b : macBytes) {
-
res1.append(String.format(
"%02X:", b));
-
}
-
-
if (res1.length() >
0) {
-
res1.deleteCharAt(res1.length() -
1);
-
}
-
return res1.toString();
-
}
-
}
catch (
Exception ex) {
-
ex.printStackTrace();
-
}
-
return
null;
-
}
注意網路介面的Name有很多:dummy0、p2p0、wlan0….其中wlan0就是我們需要WiFi mac地址。這個方法Android 7.0及其以上版本都可以獲取到。
這期需求,要求從系統裝置上獲取一個唯一碼作為當前登入使用者的唯一標識,最後決定採用mac地址。