/**
* 获取设备MAC地址
* ***/
/**
* 获取MAC地址
*
* @param context
* @return
*/
public static String getMacAddress(Context context) {
String mac = "02:00:00:00:00:00";
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
mac = getMacDefault(context);
} else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && Build.VERSION.SDK_INT < Build.VERSION_CODES.N) {
mac = getMacAddress();
} else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
mac = getMacFromHardware();
}
return mac;
}
/**
* 遍历循环所有的网络接口,找到接口是 wlan0
* 必须的权限 <uses-permission android:name="android.permission.INTERNET" />
* @return
*/
private static String getMacFromHardware() {
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 "";
}
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 e) {
e.printStackTrace();
}
return "02:00:00:00:00:00";
}
/**
* Android 6.0(包括) - Android 7.0(不包括)
* @return
*/
private static String getMacAddress() {
String WifiAddress = "02:00:00:00:00:00";
try {
WifiAddress = new BufferedReader(new FileReader(new File("/sys/class/net/wlan0/address"))).readLine();
} catch (IOException e) {
e.printStackTrace();
}
return WifiAddress;
}
/**
* Android 6.0 之前(不包括6.0)
* 必须的权限 <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
* @param context
* @return
*/
private static String getMacDefault(Context context) {
String mac = "02:00:00:00:00:00";
if (context == null) {
return mac;
}
WifiManager wifi = (WifiManager) context.getApplicationContext()
.getSystemService(Context.WIFI_SERVICE);
if (wifi == null) {
return mac;
}
WifiInfo info = null;
try {
info = wifi.getConnectionInfo();
} catch (Exception e) {
}
if (info == null) {
return null;
}
mac = info.getMacAddress();
if (!TextUtils.isEmpty(mac)) {
mac = mac.toUpperCase(Locale.ENGLISH);
}
return mac;
}
安卓获取设备MAC地址 6.0之前+6.0,7.0+7.0之后
最新推荐文章于 2023-01-05 17:18:19 发布