유선 WLAN Bluetooth MAC 주소 얻기
/**
* 获取有线MAC地址
*/
public static String getEthernetMac() {
try {
Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
while (interfaces.hasMoreElements()) {
NetworkInterface netWork = interfaces.nextElement();
if (!netWork.getName().equals("eth0")) {
continue;
}
byte[] macBytes = netWork.getHardwareAddress();
if (macBytes == null) {
return "";
}
StringBuilder res1 = new StringBuilder();
for (byte b : macBytes) {
res1.append(String.format("%02X:", b));
}
if (!TextUtils.isEmpty(res1)) {
res1.deleteCharAt(res1.length() - 1);
}
return res1.toString();
}
} catch (Exception e) {
e.printStackTrace();
}
return "";
}
/**
* 获取蓝牙 MAC 地址
*
* @return
*/
public static String getBtMac() {
return BluetoothAdapter.getDefaultAdapter().getAddress();
}
/**
* 获取 WiFi MAC地址 避免wifi关闭时获取到”02:00:00:00:00:00“
*/
public static String getWirelessMacAddress(Context context) {
WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
WifiInfo wifiInfo = wifiManager.getConnectionInfo();
String wifiMacAddress = "NA";
if (wifiInfo != null) {
if ("02:00:00:00:00:00".equals(wifiInfo.getMacAddress())) {
wifiMacAddress = getMacAddress();
} else {
wifiMacAddress = wifiInfo.getMacAddress();
}
}
return wifiMacAddress == null ? "NA" : wifiMacAddress.toUpperCase();
}
private static String getMacAddress() {
String address = null;
try {
Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
while (interfaces.hasMoreElements()) {
NetworkInterface netWork = interfaces.nextElement();
byte[] by = netWork.getHardwareAddress();
if (by == null || by.length == 0) {
continue;
}
StringBuilder builder = new StringBuilder();
for (byte b : by) {
builder.append(String.format("%02X:", b));
}
if (builder.length() > 0) {
builder.deleteCharAt(builder.length() - 1);
}
String mac = builder.toString();
if (netWork.getName().equals("wlan0")) {
address = mac;
}
}
} catch (SocketException e) {
e.printStackTrace();
}
return address;
}