转载地址:https://blog.csdn.net/yushuangping/article/details/83245847
版权声明:本文为博主原创文章,未经博主允许不得转载。 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及其以上版本都可以获取到。
版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/yushuangping/article/details/83245847
这期需求,要求从系统设备上获取一个唯一码作为当前登录用户的唯一标识,最后决定采用mac地址。